XHProf PHP Profiler Full Usage Example

Last updated:

After installing XHProf as instructed here, this is how you'd go about actually using it:

create a directory called xhprof under your home directory:

mkdir ~/xhprof

change ownership of the created directory to avoid permission problems:

sudo chown www-data xhprof/ -R

add this to your php.ini config file:

xhprof.output_dir="/home/<your_username>/xhprof"

where <your_username> is your linux username. This will be the directory where the reports will be saved.

now download this which is the actual project.

unzip the downloaded file

unzip facebook-xhprof-270b75d.zip

rename it to "xhprof".

mv facebook-xhprof-270b75d xhprof

now move the directory to your web root:

sudo mv xhprof/ /var/www

cd to your web root:

cd /var/www
Twitter Linkedin YC Hacker News Reddit

change ownership of the xhprof directory to avoid permission problems:

sudo chown www-data xhprof/ -R 

Now we are going to create the script to profile; we are going to profile the running of a for loop with some code inside; you can create the script anywhere; I'm going to create it at localhost/test/index.php:

<?php
    $XHPROF_ROOT = "/var/www/xhprof";
    include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
    include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";
    // start profiling
    xhprof_enable();
    for ($index = 0; $index < 1000; $index++) {
        $x = array(1,2,3,4);
        array_reverse($x);
     }
    //end profiling 
    $xhprof_data = xhprof_disable();
    $xhprof_runs = new XHProfRuns_Default();
    $run_id = $xhprof_runs->save_run($xhprof_data, "foobar");
?>

open that script in your browser to run it.

you should see a blank screen if you had no errors.

now cd to the directory we have created to store the created reports and list the contents:

cd ~/xhprof; ls;

you will probably see something like this: 5019d4829b80b.foobar.xhprof.

That's the report created by XHProf. To look at the results, we will open the following url on a browser:

http://localhost/xhprof/xhprof_html/index.php?run=5019d4829b80b&source=foobar
Twitter Linkedin YC Hacker News Reddit

now the value for the run parameter on the url will be the the timestamp that you saw when you listed the contents of the report directory.

Dialogue & Discussion