我們的測試環境是 Mac, php71, 安裝也很簡單:
brew install php71; brew install homebrew/php/php71-xdebug
通過 brew 安裝的我們可以在 /usr/local/etc/php/7.1/conf.d 目錄下找到xdebug擴展的配置文件,我們需要添加 profiler 的相關配置:
xdebug.profiler_output_dir 很明顯是用於存放生成的文件的路徑
xdebug.profiler_enable profiler功能的開關,默認值0,如果設為1,則每次請求都會生成一個性能報告文件。
xdebug.profiler_enable_trigger 默認值也是0,如果設為1 則當我們的請求中包含XDEBUG_PROFILE參數時才會生成性能報告文件。例如http://localhost/index.php?XDEBUG_PROFILE=1(當然我們必須關閉xdebug.profiler_enable)。使用該功能就捕獲不到頁面發送的ajax請求,如果需要捕獲的話我們就可以使用xdebug.profiler_enable功能。
xdebug.profiler_output_name 生成的文件的名字,默認 cachegrind.out.%t.%p
配置好后,我們就可以開始嘗試了,比如我們基於thinkphp5寫了一個測試程序,
public function t()
{
$p = $this->request->param();
$this->t1();
$this->t2();
$this->t3();
$this->t1();
$this->t1();
return json($p);
}
public function t1()
{
for ($i = 0; $i < 3; $i++) {
sleep(1);
}
}
public function t2()
{
for ($i = 0; $i < 5; $i++) {
sleep(1);
}
}
public function t3()
{
for ($i = 0; $i < 8; $i++) {
sleep(1);
}
}
然后通過瀏覽器訪問一下。OK,我們再去我們配置的 xdebug.profiler_output_dir 目錄下面查看一下,看到有一些文件生成了。當然這些文件我們直接看可能很費勁,我們需要借助一些圖形化的分析工具---qcachegrind(Mac上我們用這個,如果是Linux就用 kcachegrind) , 在Mac上我們直接用 brew install graphviz; brew install qcachegrind 安裝就行。但是 作分析的時候 "Call Graph" 功能可能用不了。后來找到這篇文章How to install qcachegrind (kcachegrind) on Mac OSX Snow Leopard 有解決的辦法:
sudo ln -s /usr/local/bin/dot /usr/bin/dot
用 qcachegrind 打開生成的文件,可以看到下面的結果:
通過這個圖我們一眼就能發現t方法的耗時最終都在 php的sleep方法上面。是不是有簡單,又高效。qcachegrind 還有很多其它的功能,歡迎留言分享。


