调试PHP时,XDebug一直是大众的不二选择,搭配上Webgrind,可以获得不错的效果。今天看某人的栖息地里的介绍,才发现了XHProf,于是体验了一下,感觉很酷,与XDebug相比,运行更轻便,表现更易懂,下面记录一下体验过程。

安装XHProf:

wget http://pecl.php.net/get/xhprof-0.9.2.tgz
tar zxf xhprof-0.9.2.tgz
cd xhprof-0.9.2
cp -r xhprof_html xhprof_lib <directory_for_htdocs>
cd extension
phpize
./configure
make
make install

编辑php.ini:

[xhprof]
extension=xhprof.so
;
; directory used by default implementation of the iXHProfRuns
; interface (namely, the XHProfRuns_Default class) for storing
; XHProf runs.
;
xhprof.output_dir=<directory_for_storing_xhprof_runs>

重启服务让修改生效,现在就可以使用XHProf了,不过为了显示效果更炫,最好继续安装Graphviz。

安装Graphviz:

wget http://www.graphviz.org/pub/graphviz/stable/SOURCES/graphviz-2.24.0.tar.gz
tar zxf graphviz-2.24.0.tar.gz
cd graphviz-2.24.0
./configure
make
make install

安装完成后,会生成/usr/local/bin/dot文件,你应该确保路径在PATH环境变量里,以便XHProf能找到它。

使用XHProf:

// start profiling
xhprof_enable();

// run program
....

// stop profiler
$xhprof_data = xhprof_disable();

//
// Saving the XHProf run
// using the default implementation of iXHProfRuns.
//
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
include_once $XHPROF_ROOT . "/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_foo");

echo "---------------\n".
"Assuming you have set up the http based UI for \n".
"XHProf at some address, you can view run at \n".
"http://<xhprof-ui-address>/index.php?run=$run_id&source=xhprof_foo\n".
"---------------\n";

如此一来,会在上面设定的xhprof.output_dir目录里生成名字类似49bafaa3a3f66.xhprof_foo的数据文件,可以很方便的通过Web方式浏览效果:

http://<xhprof-ui-address>/index.php?run=49bafaa3a3f66&source=xhprof_foo

目前显示的是表格形式的显示,点击页面上的[View Full Callgraph],就能看到精美的图片显示了。

补充:发现一个名为XLOG的扩展,看上去不错,可以记录URL信息。和XDEBUG这样的扩展相比,XLOG更轻便,所以部署在生产服务器上不会对性能造成过大影响。