1. 程式人生 > >使用xhprof分析php7性能

使用xhprof分析php7性能

們的 更新 def output light list charset highlight 性能分析

Xhprof是facebook開源出來的一個php輕量級的性能分析工具,跟Xdebug類似,但性能開銷更低,還可以用在生產環境中,也可以由程序開關來控制是否進行profile。

對於還在使用php5的朋友們,可以安裝pecl的xhprof擴展

http://pecl.php.net/package/xhprof

但是因為長時間不更新,針對php7已無法正常安裝,可以使用下的地址

https://github.com/longxinH/xhprof/releases

  

一、安裝xhprof

下載xhprof源碼

wget https://github.com/longxinH/xhprof/archive/v2.1.0.tar.gz

解壓源碼包

tar xf v2.1.0.tar.gz

進入目錄

cd xhprof-2.1.0/extension

運行phpize,請自行修改你們的phpize路徑

/data/nmp/php7/bin/phpize

運行configure,請自行修改你們的php-config路徑

./configure --with-php-config=/data/nmp/php7/bin/php-config

編譯安裝

make && make install

修改php.ini配置,如果extension_dir配置了就不用再配置了,如果沒配置,則把該目錄指向,擴展編譯安裝後顯示的路徑。

extension_dir = "/data/nmp/php7/lib/php/extensions/no-debug-zts-20170718"

[xhprof]
extension = xhprof.so
xhprof.output_dir = /tmp/xhprof

  

二、配置xhprof

我們把擴展目錄下的xhprof_html和xhprof_lib復制出來,單獨存放到一個目錄中。

cp -a xhprof_html /data/wwwroot/xhprof
cp -a xhprof_lib /data/wwwroot/xhprof

針對要分析的項目,可以把如下代碼添加到入口文件中:

//開啟性能分析
xhprof_enable(XHPROF_FLAGS_MEMORY | XHPROF_FLAGS_CPU);
//php中止時運行的函數
register_shutdown_function(function () {
    //停止性能分析
    $xhprof_data = xhprof_disable();
    if (function_exists(‘fastcgi_finish_request‘)) {
        fastcgi_finish_request();
    }
    //引入xhprof庫文件,路徑請自行修改
    $XHPROF_ROOT = realpath(dirname(__FILE__) . ‘/xhprof‘);
    include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
    include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";
    $xhprof_runs = new XHProfRuns_Default();
    //導出性能分析數據,默認xhprof.output_dir指定的目錄
    $run_id = $xhprof_runs->save_run($xhprof_data, ‘xhprof‘);
});

數據默認會導出到xhprof.output_dir指定目錄,所以需創建該目錄,並給予相關權限  

mkdir /tmp/xhprof
chmod -R 777 /tmp/xhprof

  

三、配置虛擬主機,用來查看分析日誌

server {
    listen       80;
    server_name  xhprof.xxx.com;
    charset utf-8;
 
    root   /data/wwwroot/xhprof/xhprof_html;
    index  index.html index.htm index.php;

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

我們可以通過訪問xhprof.xxx.com來查看分析日誌了。

如果點擊 [View Full Callgraph] 無法查看,則需裝如下工具:

yum install -y libpng
yum install -y graphviz

如果上面安裝完後,還是無法顯示,並報如下錯誤:

failed to execute cmd: " dot -Tpng". stderr: `Format: "png" not recognized. 
Use one of: canon cmap cmapx cmapx_np dot eps fig gv imap imap_np ismap pic plain plain-ext pov ps ps2 svg svgz tk vml vmlz xdot ‘

我們需要手動安裝 graphviz

https://graphviz.gitlab.io/_pages/Download/Download_source.html

下載源碼包,並編譯安裝

tar xf graphviz.tar.gz
cd graphviz-2.40.1
./configure
make
make install

  

  

使用xhprof分析php7性能