php性能分析利器:xhprof

xhprof是facebook團隊開發的用於研究php性能的擴展,而且提供了圖形化的界面展現性能參數和過程。對於各類php的項目的性能瓶頸研究有必定幫助,值得一用。php

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

  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_foonginx

而後訪問這個連接就能夠看到性能報告列表了,其中重點關注Calls(調用次數)以及Excl.Wall Time(執行時間)兩列。以下圖圖1所示,能夠看到每一個方法被調用的狀況。

此外還提供了調用圖,更加直觀,如圖2所示,紅色部分表示耗時很大的環節,也是性能優化須要重點關注的地方。
瀏覽器

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

相關文章
相關標籤/搜索