PHP性能分析工具XHProf安装使用教程

HProf是facebook开源出来的一个php轻量级的性能分析工具,跟Xdebug类似,但性能开销更低,还可以用在生产环境中,也可以由程序开关来控制是否进行profile。基于浏览器的性能分析用户界面能更容易查看,或是与同行们分享成果。也能绘制调用关系图。在数据收集阶段,它记录调用次数的追踪和包容性的指标弧在动态callgraph的一个程序。

它独有的数据计算的报告/后处理阶段。在数据收集时,XHProfd通过检测循环来处理递归的函数调用,并通过给递归调用中每个深度的调用一个有用的命名来避开死循环。

XHProf的轻量级性质和汇聚功能,使得它非常适合用于收集“生产环境”的性能统计数据的统计。

1. 安装XHProf,代码如下:

  1. wget http://pecl.php.net/get/xhprof-0.9.2.tgz
  2. tar zxf xhprof-0.9.2.tgz
  3. cd xhprof-0.9.2
  4. cp -r xhprof_html xhprof_lib <directory_for_htdocs>
  5. cd extension
  6. phpize
  7. ./configure
  8. make
  9. make install

2. 配置 php.ini 文件,代码如下:

  1. [xhprof]
  2. extension=xhprof.so
  3. ;
  4. ; directory used by default implementation of the iXHProfRuns
  5. ; interface (namely, the XHProfRuns_Default class) for storing
  6. ; XHProf runs.
  7. ; 记得<directory_for_storing_xhprof_runs>WEB要有写入权限
  8. xhprof.output_dir=<directory_for_storing_xhprof_runs>

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

3. 安装Graphviz,代码如下:

  1. wget http://www.graphviz.org/pub/graphviz/stable/SOURCES/graphviz-2.26.3.tar.gz
  2. tar zxf graphviz-2.26.3.tar.gz
  3. cd graphviz-2.26.3
  4. ./configure
  5. make
  6. make install

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

4. 应用XHProf,代码如下:

  1. xhprof_enable();//打开xhprof
  2. /******程序逻辑 Start******/
  3. function test1(){
  4. sleep(3);
  5. return;
  6. }
  7. function test2(){
  8. test1();
  9. }
  10. function test3(){
  11. test2();
  12. }
  13. function p(){
  14. echo '<h3>xhprof test</h3>';
  15. }
  16. p();
  17. test3();
  18. /******程序逻辑 End******/
  19. $xhprof_data = xhprof_disable();//关闭xhprof
  20. //保存xhprof数据
  21. include_once '../xhprof_lib/utils/xhprof_lib.php';
  22. include_once '../xhprof_lib/utils/xhprof_runs.php';
  23. $xhprof_runs = new XHProfRuns_Default();
  24. $xhprof_source = 'xhprof_test';
  25. $run_id = $xhprof_runs->save_run($xhprof_data, $xhprof_source);
  26. $report_url = 'http://xhprof.rebill.info/index.php?run='.$run_id.'&source='.$xhprof_source;
  27. echo '<br>';
  28. echo 'view the performance report:<a href="'.$report_url.'" target="_blank">'.$report_url.'</a>';

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

http://xhprof.rebill.info/index.php?run=4c236583ef490&source=xhprof_test

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

在线测试体验地址:http://xhprof.rebill.info/test.php