XHProf 是 Facebook 開源的輕量級 PHP 性能分析工具,類似 Xdebug 但開銷極低(<5%),可安全用於生產環境。支援函數級調用統計、記憶體/CPU 分析、調用關係圖視覺化。
# 下載源碼
wget https://pecl.php.net/get/xhprof-0.9.2.tgz
tar zxf xhprof-0.9.2.tgz
cd xhprof-0.9.2
# 複製 Web UI 到文檔根目錄
cp -r xhprof_html xhprof_lib /var/www/html/xhprof
# 編譯擴充
cd extension
phpize
./configure --with-php-config=/usr/bin/php-config
make && make install
[xhprof]
extension=xhprof.so
; 必須可寫入,建議獨立目錄
xhprof.output_dir=/var/tmp/xhprof
mkdir -p /var/tmp/xhprof
chown www-data:www-data /var/tmp/xhprof
systemctl restart php-fpm # 或對應服務
# Ubuntu/Debian
apt-get install graphviz
# CentOS/RHEL
yum install graphviz
# 驗證
dot -V
# 確保 /usr/bin/dot 在 PATH 中
<?php
// 啟動分析
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
// ==== 業務邏輯開始 ====
function test1() { sleep(1); }
function test2() { test1(); }
function test3() { test2(); }
function pageRender() { echo "XHProf Demo
"; }
pageRender();
test3();
// ==== 業務邏輯結束 ====
// 停止並獲取資料
$xhprof_data = xhprof_disable();
// 儲存執行資料
include_once '/var/www/html/xhprof/xhprof_lib/utils/xhprof_lib.php';
include_once '/var/www/html/xhprof/xhprof_lib/utils/xhprof_runs.php';
$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, 'my_app');
$report_url = "https://your-domain/xhprof/xhprof_html/index.php?run=$run_id&source=my_app";
echo "查看性能報告";
<?php
// 僅 1% 請求採樣,降低開銷
if (mt_rand(1, 100) === 1) {
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
register_shutdown_function(function() {
$data = xhprof_disable();
$runs = new XHProfRuns_Default();
$runs->save_run($data, 'production_sampling');
});
}
| 欄位 | 含義 | 關注重點 |
|---|---|---|
| Calls | 函數被調用次數 | 高頻調用點 |
| Wall Time (wt) | 牆鐘時間(含 I/O 等待) | 總耗時瓶頸 |
| CPU Time (ct) | CPU 實際執行時間 | 計算密集熱點 |
| Memory (mu) | PHP 記憶體使用量 | 記憶體洩漏、大物件 |
| Peak Memory (pmu) | 峰值記憶體 | 記憶體尖峰 |
| Incl. / Excl. | 含/不含子調用 | Incl 找總瓶頸,Excl 找函數本身開銷 |
點擊報告頁面 [View Full Callgraph] 生成圖片,需 Graphviz 支援。圖中:
# URL 參數添加 run2=另一個run_id
https://.../index.php?run=run1&run2=run2&source=my_app
<?php
// 僅分析特定命名空間
xhprof_enable(XHPROF_FLAGS_CPU, array('ignored_functions' => array('call_user_func', 'spl_autoload_call')));
# 測試階段自動生成報告並對比基準
php -d xhprof.output_dir=/tmp/xhprof vendor/bin/phpunit --bootstrap bootstrap.php tests/
# 解析最新 run_id,與基準對比,若關鍵指標退化 > 20% 則失敗
xhprof.output_dir 權限、Graphviz 路徑、PHP 版本相容性(PHP 8 需 2.0+ 版本)xhprof.output_dir 用 tmpfs 或高性能 SSDexec() 是否被禁用、dot 命令可用php -d xdebug.profiler_enable=1:零依賴但極重XHProf 以極低開銷提供生產級性能洞察,是 PHP 性能優化工具鏈的核心組件。