調試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更輕便,所以部署在生產服務器上不會對性能造成過大影響。