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.php
和xhprof_runs.php
兩個文件copy到項目目錄中,在這裏我拷貝到了網站根目錄下做爲測試,實際項目使用中能夠根據本身的習慣封裝成function。web
將xhprof/xhprof_html 做爲root目錄配置一個vhost,如xhprof.test.com
。shell
在測試中我將入口文件中入口函數做爲測試單元包裹起來,在項目中可一個根據實際狀況本身決定粒度粗細。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
點擊中間的 View Full Callgraph,能夠查看調用順序及性能分析(單位是微秒)app
紅色的就是佔用時間較多的函數函數
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報告(二)