MAMP(PHP7)使用xhprof性能分析工具

MAMP(PHP7)使用xhprof性能分析工具

xhprof是Facebook开源的一个轻量级PHP性能分析工具,相似于Xdebug,可是更直观,因为pecl的xhprof最高只支持到php5.4,因此咱们使用github版本php

安装

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最后一行加入:html

[xhprof]
extension = xhprof.so
xhprof.output_dir = /tmp/xhprof
复制代码

重启php-fpm并在/tmp目录下新建xhprof文件夹,给权限。git

执行php --ri xhprof ,有以下输出证实安装成功github

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.phpxhprof_runs.php两个文件copy到项目目录中,在这里我拷贝到了网站根目录下做为测试,实际项目使用中能够根据本身的习惯封装成function。web

将xhprof/xhprof_html 做为root目录配置一个vhost,如xhprof.test.comshell

在测试中我将入口文件中入口函数做为测试单元包裹起来,在项目中可一个根据实际状况本身决定粒度粗细。bash

<?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中查看结果php7

xhprofindex

xhproffunc

点击中间的 View Full Callgraph,能够查看调用顺序及性能分析(单位是微秒)app

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报告(二)