Generally, the process of profiling a chunk of code using XHProf goes as follows:
- Call
xhprof_enable()
- Run the code you want profiled
- Once the code has finished running, call
xhprof_disable()
. That function will return the profiler data, which you can either display to the screen (not recommended), or…
- Store the profiler data to a file by creating a new
XHProfRuns_Default();
object and calling its save_run
method.
In the case below, I’m profiling a module that implements a few Drush commands from the command line which I’d like to optimize. So I created _modulename_xhprof_enable()
and _modulename_xhprof_disable()
functions – the names don’t matter here – and then added a --profile
flag to my Drush command options which, when it is set to true, calls my custom enable/disable functions before and after the Drush command runs.
Here’s what those look like in full:
<?php
/**
* Helper function to enable xhprof.
*/
function _mymodule_enable_xhprof() {
if (function_exists('xhprof_enable')) {
// Tell XHProf to track both CPU time and memory usage
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY,
array(
// Don't treat these functions as separate function callss
// in the results.
'ignored_functions' => array('call_user_func',
'call_user_func_array',
),
));
}
}
/**
* Helper function to disable xhprof and save logs.
*/
function _mymodule_disable_xhprof() {
if (function_exists('xhprof_enable')) {
$xhprof_data = xhprof_disable();
//
// Saving the XHProf run
// using the default implementation of iXHProfRuns.
//
include_once "/usr/share/php/xhprof_lib/utils/xhprof_lib.php";
include_once "/usr/share/php/xhprof_lib/utils/xhprof_runs.php";
$xhprof_runs = new XHProfRuns_Default();
// Save the run under a namespace "xhprof_foo".
//
// **NOTE**:
// By default save_run() will automatically generate a unique
// run id for you. [You can override that behavior by passing
// a run id (optional arg) to the save_run() method instead.]
// .
$run_id = $xhprof_runs->save_run($xhprof_data, 'xhprof_mymodule');
echo "---------------\nAssuming you have set up the http based UI for \nXHProf at some address, you can view run at \nhttp://mywebsiteurl.dev/xhprof/index.php?run=$run_id&source=xhprof_mymodule\n---------------\n";
}
}
The echo
command here works fine for a Drush command, but for other tasks you could log the run url using watchdog.
Note: Another way to run XHProf on a Drupal site is using the XHProf module, but I haven’t had great luck with that.