天天看點

PHP性能監測的工具介紹 - XHProf

XHProf

這個軟體本是Facebook内部的一個應用工具,2009年3月份開源,為PHP的性能監測提供了很好的工具。官方的介紹中提到:

XHProf's light-weight nature and aggregation capabilities make it well suited for collecting "function-level" performance statistics from production environments.

可以先來看看 XHProf 提供的圖形界面的截圖

XHProf的一些特性:

1、Flat Profile. 提供函數級的彙總資訊,比如調用次數、執行時間、記憶體使用、CPU占用等。

PHP性能監測的工具介紹 - XHProf

2、Hierarchical Profile。 對每個程式,進行了父級調用和子級調用的分解。

3、Diff Reports(差異報告)。有很多種情況,我們希望能夠對比,比如新版本比舊版本提升了多少速度,兩個版本的差距究竟在哪裡。Diff Report 就是這樣的工具,接收兩個輸入,并且分别給出各自的 Flat Profile 和 Hierarchical Profile 報告。

4、Callgraph View(調用視圖)。性能監測的資料可以繪制成調用視圖,友善我們檢視。

PHP性能監測的工具介紹 - XHProf

5、Memory Profile(記憶體監控)。這個特性幫助我們了解PHP如何配置設定和釋放記憶體。值得注意的是,XHProf并不是嚴格的監測記憶體的配置設定和釋放動作,而是計算每個函數進入和退出時的記憶體狀況,這是一個相對簡單的實作方式,但是基本上也能夠滿足我們日常的監控需求。

6、如何處理外部檔案。XHProf将 include,require,include_once,require_once進來的檔案視作是一個 function。

XHProf目前隻支援一個級别的函數追蹤,但是貌似也沒有特别大的影響。

XHProf的安裝配置

php.ini file: You can update your php.ini file to automatically load your extension. Add the following to your php.ini file.

 

xhprof的使用也很簡單,隻要将需要監控的腳本放在 xhprof_enable() 和 xhprof_disable() 中間,就可以得到相應的結果,同時也提供了一些參數可以讓我們設定是否監控 Memory, CPU 的使用,是否監控PHP内置的函數,從 0.9.2 之後,還可以設定跳過一些特定的函數。

XHProf 生成的資料,可以用 XHProf UI 來進行簡單的顯示。

XHProf使用也很簡單,下面是一個官方的例子:

<?php function bar($x) {   if ($x > 0) {     bar($x - 1);   } } function foo() {   for ($idx = 0; $idx < 2; $idx++) {     bar($idx);     $x = strlen("abc"); xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY); foo(); $xhprof_data = xhprof_disable(); // // Saving the XHProf run // using the default implementation of iXHProfRuns. include_once "xhprof_lib/utils/xhprof_lib.php"; include_once "xhprof_lib/utils/xhprof_runs.php"; $xhprof_runs = new XHProfRuns_Default(); // Save the run under a namespace "xhprof_foo". // **NOTE**: // By default save_run() will automatically generate a unique // run id for you. [You can override that behavior by passing // a run id (optional arg) to the save_run() method instead.] $run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo"); echo "---------------\n".      "Assuming you have set up the http based UI for \n".      "XHProf at some address, you can view run at \n".      "---------------\n"; ?>

我們可以持久化記錄的資料,資料以檔案的形式儲存在指定的目錄,如下圖:

PHP性能監測的工具介紹 - XHProf

xhprof畫圖使用的dot程式需要伺服器上有libpng的環境支援,要想這部分能夠正常繪圖,需要安裝 graphviz-2.24.0、libpng才行,具體的在參考資料4中有說。

PHP性能監控,還有兩個可用的工具,一個是 XDebug,另外一個是 ZendServer,我會在接下來繼續進行介紹。

參考文檔:

1、Speed UP your php with xhprof