本教程使用的 xhprof 版本来源于 https://github.com/longxinH/xhprof 仓库。
安装 xhprof
进入 xhprof 扩展目录:cd xhprof/extension/
执行 phpize 命令准备构建环境。
运行 ./configure 进行配置。
执行 make 命令进行编译。
编译完成后,需要在 /etc/php.ini 文件中添加相应的扩展配置。
extension=xhprof.so
保存配置后,执行以下命令检查扩展是否加载成功。
php -m | grep xhprof
如果终端输出包含 xhprof,说明扩展安装成功。此时需要重启 Apache 或 php-fpm 服务以使配置生效。
运行
你可以直接运行从 GitHub 克隆下来的示例项目中的 example 目录下的测试脚本。
执行后控制台将输出如下数组结构的数据。
Array
(
[main()] => Array
(
[ct] => 1
[wt] => 9
)
)
---------------
Assuming you have set up the http based UI for
XHProf at some address, you can view run at
http:///index.php?run=592567308784c&source=xhprof_foo
然后复制index.php后面的?run=592567308784c&source=xhprof_foo
将该参数追加到本地部署的 xhprof HTML UI 地址之后进行访问。
xhprof_html/index.php?run=592567308784c&source=xhprof_foo
浏览器中将显示性能分析的结果页面。

点击页面中间的 View Full Callgraph 按钮,即可查看可视化的性能分析调用图。
报错
如果在生成图片时遇到错误:failed to execute cmd:" dot -Tpng". stderr:sh: dot:command not found。
//解决方案yum install graphviz
随机应变
例如,如果你想对自己开发的项目(如某个框架)进行性能分析。
需要将 xhprof_lib/utils/ 目录下的两个核心文件。
xhprof_lib.php和xhprof_runs.php复制到项目入口文件的同级目录下,然后在入口文件起始位置添加 [[a1]]
// start profiling
xhprof_enable();
在入口文件结束位置添加 [[a2]]
// stop profiler
$xhprof_data = xhprof_disable();
// display raw xhprof data for the profiler run
print_r($xhprof_data);
include_once "xhprof_lib.php";
include_once "xhprof_runs.php";
// save raw data for this profiler run using default
// implementation of iXHProfRuns.
$xhprof_runs = new XHProfRuns_Default();
// save the run under a namespace "xhprof_foo"
$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:///index.php?run=$run_id&source=xhprof_foo\n".
"---------------\n";
这样即可得到类似于示例中所示的 URL,再次访问该 URL。
http://***/xhprof_html/index.php?run=*****&source=xhprof_foo
你将看到如下所示的性能分析页面。

查看图片

图中红色的部分为性能比较低,耗时比较长的部分,我们可以根据根据哪些函数被标记为红色对系统的代码进行优化
补充
Function Name:方法名称。
Calls:方法被调用的次数。
Calls%:方法调用次数在同级方法总数调用次数中所占的百分比。
Incl.Wall Time(microsec):方法执行花费的时间,包括子方法的执行时间。(单位:微秒)
IWall%:方法执行花费的时间百分比。
Excl. Wall Time(microsec):方法本身执行花费的时间,不包括子方法的执行时间。(单位:微秒)
EWall%:方法本身执行花费的时间百分比。
Incl. CPU(microsecs):方法执行花费的CPU时间,包括子方法的执行时间。(单位:微秒)
ICpu%:方法执行花费的CPU时间百分比。
Excl. CPU(microsec):方法本身执行花费的CPU时间,不包括子方法的执行时间。(单位:微秒)
ECPU%:方法本身执行花费的CPU时间百分比。
Incl.MemUse(bytes):方法执行占用的内存,包括子方法执行占用的内存。(单位:字节)
IMemUse%:方法执行占用的内存百分比。
Excl.MemUse(bytes):方法本身执行占用的内存,不包括子方法执行占用的内存。(单位:字节)
EMemUse%:方法本身执行占用的内存百分比。
Incl.PeakMemUse(bytes):Incl.MemUse峰值。(单位:字节)
IPeakMemUse%:Incl.MemUse峰值百分比。
Excl.PeakMemUse(bytes):Excl.MemUse峰值。单位:(字节)
EPeakMemUse%:Excl.MemUse峰值百分比。
以上就是PHP7下安装并使用xhprof性能分析工具的详细内容,更多关于PHP7下安装并使用xhprof的资料请关注本站其它相关文章!