php效能分析利器:xhprof

freephp發表於2021-02-17

xhprof是facebook團隊開發的用於研究php效能的擴充套件,並且提供了圖形化的介面展示效能引數和過程。對於各種php的專案的效能瓶頸研究有一定幫助,值得一用。

我在上一篇《Dockerfile搭建極簡LNMP環境》一文中已經建立好了LNMP環境,下面是基於這個容器進行xhprof的安裝和使用。

  1. 安裝xhprof

編寫如下install_xhprof.sh指令碼,分為編譯安裝、設定擴充套件、部署前端模組檔案三大步驟。

# get the source codes

wget https://pecl.php.net/get/xhprof-2.2.3.tgz
tar xvf xhprof-2.2.3.tgz
#mv xhprof-2.2.3 xhprof
cd xhprof/extension
phpize
./configure --enable-xhprof
make && make install

# enable xhprof in php modules
echo "extension=xhprof.so" > /etc/php/7.4/cli/conf.d/20-xhprof.ini

echo "xhprof.output_dir=/tmp" >> /etc/php/7.4/cli/conf.d/20-xhprof.ini
# enable xhprof in php-fpm modules
cp /etc/php/7.4/cli/conf.d/20-xhprof.ini /etc/php/7.4/fpm/conf.d/xhprof.ini

# restart php-fpm service
service php7.4-fpm restart
# move fronted-codes to nginx's path
mkdir -p /var/www/xhprof
cp -r /installsofts/xhprof/xhprof_html  /var/www/xhprof/
cp -r /installsofts/xhprof/xhprof_lib   /var/www/xhprof/
  1. 新增虛擬主機到Nginx配置
    然後在/etc/nginx/site-enabled目錄下建立一個名為xhprof.conf的配置檔案,其內容如下:
server{
     listen 80;
     server_name xhprof.alice.show;
     location / {
          root /var/www/xhprof;
          index index.html index.php;
     }
     location ~ \.php$ {
          root /var/www/xhprof;
          include snippets/fastcgi-php.conf;
          fastcgi_pass unix:/run/php/php7.4-fpm.sock;
     }
 }
  1. 編寫測試程式碼
    萬事俱備只欠東風,下面編寫一個測試程式碼來呼叫到xhprof:
<?php

include_once "./xhprof_lib/utils/xhprof_lib.php";
include_once "./xhprof_lib/utils/xhprof_runs.php";

function test($max)
{
    for ($idx = 0; $idx < $max; $idx++) {
        echo '2333' . "\r\n";
    }
}

function a()
{
    test(rand(1000,2000));
}

// 開啟xhprof
xhprof_enable();

a();

// 收集profilling資料
$xhprof_data = xhprof_disable();
$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo");
# 列印出結果報告的URL
echo "\nhttp://xhprof.alice.show/xhprof_html/index.php?run=$run_id&source=xhprof_foo\n";

在瀏覽器中訪問http://xhprof.alice.show/test2.php,就可以看到頁面最後列印出了類似輸出:
http://xhprof.alice.show/xhprof_html/index.php?run=602c9cfb679ee&source=xhprof_foo

然後訪問這個連結就可以看到效能報告列表了,其中重點關注Calls(呼叫次數)以及Excl.Wall Time(執行時間)兩列。如下圖圖1所示,可以看到每個方法被呼叫的情況。

此外還提供了呼叫圖,更加直觀,如圖2所示,紅色部分表示耗時很大的環節,也是效能優化需要重點關注的地方。

感謝Facebook團隊開源出這麼好用的效能分析工具,php效能之路還將繼續!

相關文章