PHP 效能檢測工具:XHProf

2020093017:39


XHProf 是 facebook 開發的 PHP 效能追蹤軟體 profiler
可顯示程式執行時,各 function 花費的時間、記憶體、CPU 消耗裝況..可用來找出瓶頸、評估軟體改善

XHProf is a function-level hierarchical profiler for PHP and has a simple HTML based navigational interface. The raw data collection component is implemented in C (as a PHP extension). The reporting/UI layer is all in PHP. It is capable of reporting function-level inclusive and exclusive wall times, memory usage, CPU times and number of calls for each function. Additionally, it supports ability to compare two runs (hierarchical DIFF reports), or aggregate results from multiple runs.


XHProf 下載
http://pecl.php.net/package/xhprof

另有其他人fork 的版本:

可以試試
https://github.com/longxinH/xhprof   支援 php 7/8

https://github.com/tideways/php-xhprof-extension  支援 php 7/8

 
安裝

# wget
http://pecl.php.net/get/xhprof-2.2.3.tgz
# zcat xhprof-2.2.3.tgz | tar xfv -
# cd
xhprof-2.2.3

# cd extension
# phpize
# ./configure
# make
# make install


# cp -r xhprof_html xhprof_lib ~www/htdocs



/usr/local/lib/php.ini
加 3 行
[xhprof]
extension=xhprof.so
xhprof.output_dir= /tmp
  (資料暫存檔存放位置,注意讀寫權限)



若要以圖形來顯示 profile
安裝 Graphviz

# wget http://www.graphviz.org/pub/graphviz/stable/SOURCES/graphviz-2.24.0.tar.gz
# zcat graphviz-2.24.0.tar.gz | tar xfv -
# cd graphviz-2.24.0
# ./configure
# make
# make install


使用方式:
以 wordpress 範例,修改 index.php
<?php

xhprof_enable();


#wordpress 程式碼開始----
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );

#wordpress 程式碼結束----

$xhprof_data = xhprof_disable();

$XHPROF_ROOT='/home/wordpress/';
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();
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo");

$profiler_url = "/xhprof_html/index.php?run=$run_id&source=xhprof_testing\n";
echo "<a href=$profiler_url><b>profiling</b></a>";



report 畫面的幾個名詞:
  1. Inclusive Time (or Subtree Time): Includes time spent in the function as well as in descendant functions called from a given function.
  2. Exclusive Time/Self Time: Measures time spent in the function itself. Does not include time in descendant functions.
  3. Wall Time: a.k.a. Elapsed time or wall clock time.
  4. CPU Time: CPU time in user space + CPU time in kernel space

wordpress 執行結果: