PHP 性能分析工具XHProf使用

来源:互联网 发布:java招生 编辑:程序博客网 时间:2024/06/05 07:29

当PHP程序逻辑执行很复杂的时候,可能会带来性能上的问题,为了有效的找到影响性能的代码,推荐大家使用PHP新能分析工具XHProf,该工具能有效的分析每段代码的执行情况,非常好用

1、安装配置PHP的扩展XHProf

[plain] view plain copy 在CODE上查看代码片派生到我的代码片
  1. $ wget https://github.com/facebook/xhprof/tarball/master -O xhprof.tar.gz  
  2. $ tar zxf xhprof.tar.gz  
  3. $ cd facebook-xhprof-b8c76ac/extension/  
  4. # phpize  
  5. # ./configure --with-php-config=`/path/to/php-config`  
  6. # make && make install  
  7. # make test  
  8.   
  9.   
  10. # vi /etc/php.d/xhprof.ini  
  11. ; 内容为:  
  12. extension = xhprof.so  
  13. ; 注意:output_dir 必须存在且可写  
  14. xhprof.output_dir = /tmp/xhpro  
  15.   
  16.   
  17. 然后重启apache服务  
  18. # service php-fpm restart 或 service httpd restart   

2、使用XHProf

[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. // start profiling  
  2. xhprof_enable();  
  3.   
  4. // run program  
  5. ....  
  6.   
  7. // stop profiler  
  8. $xhprof_data = xhprof_disable();  
  9.   
  10. //  
  11. // Saving the XHProf run  
  12. // using the default implementation of iXHProfRuns.  
  13. //  
  14. include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";  
  15. include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";  
  16.   
  17. $xhprof_runs = new XHProfRuns_Default();  
  18.   
  19. // Save the run under a namespace "xhprof_foo".  
  20. //  
  21. // **NOTE**:  
  22. // By default save_run() will automatically generate a unique  
  23. // run id for you. [You can override that behavior by passing  
  24. // a run id (optional arg) to the save_run() method instead.]  
  25. //  
  26. $run_id = $xhprof_runs->save_run($xhprof_data"xhprof_foo");  
  27.   
  28. echo "---------------\n".  
  29. "Assuming you have set up the http based UI for \n".  
  30. "XHProf at some address, you can view run at \n".  
  31. "http://<xhprof-ui-address>/index.php?run=$run_id&source=xhprof_foo\n".  
  32. "---------------\n";  
  33.   
  34. 如此一来,会在上面设定的xhprof.output_dir目录里生成名字类似49bafaa3a3f66.xhprof_foo的数据文件,可以很方便的通过Web方式浏览效果:  

3、展示输出结果

在 xhprof 源码包中提供了xhprof_html 和 xhprof_lib 两个文件夹,xhprof_lib是用于 PHP 开发,而xhprof_html用于显示 xhprof 分析结果的 web 界面,访问形式如下

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