蒦嗳伱 发表于 2017-3-31 09:34:41

php代码性能分析工具:XHProf

  http://www.ooso.net/archives/522

http://www.cnblogs.com/sunvince/archive/2011/04/07/2037616.html

http://hi.baidu.com/thinkinginlamp/blog/item/f4bd08fa1a03ba9e59ee90fd.html
  XHProf是Facebook开源的一个PHP性能检测程序,里面有很多直观的数据来说明问题,比如调用次数、执行时间、内存使用、CPU占用等
  编译安装


获取源代码包

root@sourcjoy>
wget http://pecl.php.net/get/xhprof-0.9.2.tgz

解压


root@sourcjoy>
tar zxf xhprof-0.9.2.tgz
root@sourcjoy>
cd xhprof-0.9.2
复制web访问目录到web应用目录

root@sourcjoy>
cp -r xhprof_html xhprof_lib /var/www/html/
  #复制xhprof的展示页面目录和库目录到web目录下,可以为xhprof_html建个虚拟目录来访问,也可以把这两个目录拷贝到应用的根目录下。

root@sourcjoy>
cd extension/
编译插件


root@sourcjoy>
/usr/local/webserver/php/bin/phpize

root@sourcjoy>
./configure --with-php-config=/usr/local/webserver/php/bin/php-config

root@sourcjoy>
make

root@sourcjoy>
make install

  

注意:这里安装的时候可能会出现访问php.ini没权限的问题,请把php.ini的权限改成666:

chmod 666 /usr/local/webserver/php/etc/php.ini

  配置 php.ini 文件

root@sourcjoy>
vi /usr/local/webserver/php/etc/php.ini
在合适位置加入以下内容:
  

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.output_dir=/var/logs/xhprof

  重启web服务器
  为了更加清晰显示程序执行、调用结构,安装Graphviz,如果安装了Graphviz,XHProf会用比较牛的图形方式展现统计数据。
获取源码包

root@sourcjoy>
wget http://www.graphviz.org/pub/graphviz/stable/SOURCES/graphviz-2.24.0.tar.gz

root@sourcjoy>
tar zxf graphviz-2.24.0.tar.gz
root@sourcjoy>
cd graphviz-2.24.0
编译安装

root@sourcjoy>
./configure
root@sourcjoy>
make
root@sourcjoy>
make install

  接下来在要统计的php应用中加入以下语句:
xhprof_enable();
 //统计的代码部
分之前加,如果要显示CPU占用
可以加入XHPROF_FLAGS_CPU参数,内存是XHPROF_FLAGS_MEMORY,如果两个一起:XHPROF_FLAGS_CPU +
XHPROF_FLAGS_MEMORY,如:xhprof_enable(XHPROF_FLAGS_CPU +
XHPROF_FLAGS_MEMORY);

  xhprof_disable();
//统计的代码部分之后加

  这样xhprof就可以统计当前页面的函数性能情况了。xhprof会把每次访问加入统计代码的页面的性能统计结果在指定目录下生成一个文件,文件名命名方式为:本次访问的系统ID.命名空间,每次刷新页面都会重新生成一个文件,每个的系统ID都不同。
  然后通过xhprof_html目录的http访问url来查看结果。如:http://app/xhprof_html/?run=运行id&source=命名空间(其中运行ID和命名空间可以根据xhprof生成的文件名来确定)

xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
//require_once ($yii);
//Yii::createWebApplication($config)->run();
$xhprofData = xhprof_disable();
Yii::import('application.components.monitor.xhprof.XhprofLib');
Yii::import('application.components.monitor.xhprof.XHProfRunsDefault');
$xhprofRuns = new XHProfRunsDefault();
$runId = $xhprofRuns->saveRun($xhprofData, 'test');
   

以yii为例子访问方式如下:
  http://test/index.php?r=xhprof/default/index

http://test/xhprof_html/?run=4f263128d1bf6&source=test&all=1

(4f263128d1bf6是随机生成的文件名)


说明:
1. Inclusive Time :包括子函数所有执行时间。

2. Exclusive Time/Self Time:函数执行本身花费的时间,不包括子树执行时间。


3. Wall Time:花去了的时间或挂钟时间。

4. CPU Time:用户耗的时间+内核耗的时间

5.Inclusive CPU:包括子函数一起所占用的CPU

6.Exclusive CPU:函数自身所占用的CPU
  上图更直观些:
  

  
页: [1]
查看完整版本: php代码性能分析工具:XHProf