XHProf in 30 Seconds: How to get started profiling PHP

Apr 26 2013

The task was simple: I wanted to run xhprof (the Facebook-developed PHP profiler) to get some quick-and-dirty metrics on a PHP script. While xhprof is actually really easy to install and use, I had to read a surprising amount of material in order to run a simple install and write three lines of code.

To spare others the agony of cruising old Facebook docs in the Internet Archive, here's a 30 second guide to installing and using xhprof.

Installation

Install using pecl (You may need to use sudo):

$ sudo pecl install xhprof

It may tell you that you must install a specific version: sudo pecl install xhprof-0.9.2.

Once it's installed, you will need to tell PHP to use it. On Ubuntu, I created /etc/php5/apache2/conf.d/xhprof.ini with one line:

extension=xhprof.so

To get it working with Apache, restart Apache: sudo service apache2 restart.

Using

Usage is simple. To start profiling, add this to your script:

<?php
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
?>

To stop the profiler and collect the data, try this:

<?php
$prof = xhprof_disable();
?>

The $prof data is just an associative array with function call names as the key and performance information as the value.

Making Sense of the Data

Here's a print_r() dump of a simple script with one function: test().

Array
(
    [main()==>test] => Array
        (
            [ct] => 1
            [wt] => 132
            [cpu] => 0
            [mu] => 1072
            [pmu] => 0
        )

    [main()==>xhprof_disable] => Array
        (
            [ct] => 1
            [wt] => 1
            [cpu] => 0
            [mu] => 1080
            [pmu] => 0
        )

    [main()] => Array
        (
            [ct] => 1
            [wt] => 167
            [cpu] => 0
            [mu] => 4160
            [pmu] => 0
        )

)

Each entry gives the following information:

  • ct: Count. The number of times the function was called.
  • wt: Wall Time. Amount of "real world" time (from "wall clock time").
  • cpu: Number of CPU "ticks" executed for this function (a measure of CPU usage).
  • mu: Memory usage
  • pmu: Peak Memory Usage (a la get_peak_memory_usage()). This does not always seem to be accurate,

There is a built-in Web UI for xhprof, but I haven't yet tried it.

If your French is better than mine, I recommend this presentation.