MAMP(PHP7)使用xhprof性能分析工具
xhprof是Facebook开源的一个轻量级PHP性能分析工具,类似于Xdebug,但是更直观,由于pecl的xhprof最高只支持到php5.4,所以我们使用github版本。
安装
git clone https://github.com/longxinH/xhprof.git
cd xhprof/extension/
/Applications/MAMP/bin/php/php7.1.1/bin/phpize
./configure --with-php-config=/Applications/MAMP/bin/php/php7.1.1/bin/php-config
make
make install
安装完成后在php.ini最后一行加入:
[xhprof]
extension = xhprof.so
xhprof.output_dir = /tmp/xhprof
重启php-fpm并在/tmp目录下新建xhprof文件夹,给权限。
执行php --ri xhprof ,有如下输出证明安装成功
xhprof
xhprof support => enabled
Version => 2.0.1
Directive => Local Value => Master Value
xhprof.output_dir => /tmp/xhprof => /tmp/xhprof
xhprof.sampling_interval => 100000 => 100000
xhprof.sampling_depth => 2147483647 => 2147483647
使用
将xhprof/xhprof_lib/utils下xhprof_lib.php和xhprof_runs.php两个文件copy到项目目录中,在这里我拷贝到了网站根目录下作为测试,实际项目使用中可以根据自己的习惯封装成function。
将xhprof/xhprof_html 作为root目录配置一个vhost,如xhprof.test.com。
在测试中我将入口文件中入口函数作为测试单元包裹起来,在项目中可一个根据实际情况自己决定粒度粗细。
<?php
/**
* 程序入口文件
*/
//开启xhprof
xhprof_enable();
//检测PHP环境
if (PHP_VERSION < '5.2.0') die('Require PHP > 5.2.0 ');
//定义当前的网站物理路径
define('WWW_ROOT', dirname(__FILE__) . '/');
require './configs/web_config.php';
require COREFRAME_ROOT . 'core.php';
$app = load_class('application');
$app->run();
//关闭xhprof
$xhprof_data = xhprof_disable();
//引入所需文件
include_once "./xhprof_lib.php";
include_once "./xhprof_runs.php";
//保存数据
$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_test");
之后可以在刚刚新建vhost中查看结果
点击中间的 View Full Callgraph,可以查看调用顺序及性能分析(单位是微秒)
红色的就是占用时间较多的函数
报错
dot: command not found
原因:未安装graphviz
解决方法:brew install graphviz
如果安装后依旧提示此错误
在xhprof_lib/utils/callgraph_utils.php 112行中修改$process = proc_open( $cmd, $descriptorspec, $pipes, sys_get_temp_dir(), array( 'PATH' => getenv( 'PATH' ) ) );为
$process = proc_open( $cmd, $descriptorspec, $pipes, sys_get_temp_dir(), array( 'PATH' => getenv( 'PATH' ).':/usr/local/Cellar/graphviz/2.40.1/bin' ) );,将graphviz路径拼接到PATH参数中即可
性能分析
参考CSDN PHP性能监控 - 怎么看xhprof报告(二)