咱們的測試環境是 Mac, php71, 安裝也很簡單:php
brew install php71; brew install homebrew/php/php71-xdebugreact
經過 brew 安裝的咱們能夠在 /usr/local/etc/php/7.1/conf.d 目錄下找到xdebug擴展的配置文件,咱們須要添加 profiler 的相關配置:程序員
xdebug.profiler_output_dir 很明顯是用於存放生成的文件的路徑
ajax
xdebug.profiler_enable profiler功能的開關,默認值0,若是設爲1,則每次請求都會生成一個性能報告文件。thinkphp
xdebug.profiler_enable_trigger 默認值也是0,若是設爲1 則當咱們的請求中包含XDEBUG_PROFILE參數時纔會生成性能報告文件。例如http://localhost/index.php?XDEBUG_PROFILE=1(固然咱們必須關閉xdebug.profiler_enable)。使用該功能就捕獲不到頁面發送的ajax請求,若是須要捕獲的話咱們就可使用xdebug.profiler_enable功能。json
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 有解決的辦法:php7
sudo ln -s /usr/local/bin/dot /usr/bin/dot
thinkphp5
用 qcachegrind 打開生成的文件,能夠看到下面的結果:
經過這個圖咱們一眼就能發現t方法的耗時最終都在 php的sleep方法上面。是否是有簡單,又高效。qcachegrind 還有不少其它的功能,歡迎留言分享。