MAMP(PHP7)使用xhprof性能分析工具 作者: admin 时间: 2018-07-23 分类: 默认分类 ##MAMP(PHP7)使用xhprof性能分析工具 xhprof是Facebook开源的一个轻量级PHP性能分析工具,类似于Xdebug,但是更直观,由于pecl的xhprof最高只支持到php5.4,所以我们使用[github版本](https://github.com/longxinH/xhprof)。 ###安装 ```shell 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 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报告(二)](https://blog.csdn.net/loophome/article/details/77543336) 标签: 项目, 文件, bin, xhprof, php, tmp, mamp