使用 Xdebug + Webgrind 分析 PHP 程序

安裝 xdeubg zend 擴展

# yum install php-pecl-xdebug

配置 php.d/xdebug.ini

# vi /etc/php.d/xdebug.ini;加入以下內容; profilerxdebug.profiler_enable=1xdebug.profiler_enable_trigger=1xdebug.profiler_output_dir=/tmp/xdebugxdebug.profiler_output_name=cachegrind.out.%p; tracexdebug.auto_trace=1xdebug.show_exception_trace=1xdebug.trace_output_dir=/tmp/xdebugxdebug.trace_output_name=trace.%c

注:需手工創建 /tmp/xdebug 目錄且所屬用戶應爲 php-fpm 配置文件中的 user 用戶。 配置完畢,重啓 service php-fpm restart

下載 webgrind

$ cd /var/www/html/$ git clone git://github.com/jokkedk/webgrind.git

安裝 graphviz

# yum install graphviz

graphviz 附帶 dot 命令用於下文的配置。

使用 webgrind

webgrind v1.1 的版本增加了 Show Call Graph 按鈕,依賴 pythondot 命令, 類似 xhprof 的View Full Callgraph 繪製程序調用流程圖功能,相對於 xhprof 較簡潔。 更多 xhprof 信息請查看 使用 XHProf 分析你的 PHP 程序

配置 webgrind 的繪製流程圖功能,查看 pythondot 命令位置 which pythonwhich dot,編輯 webgrind/config.php,將 $pythonExecutable = '/usr/bin/python'$dotExecutable = '/usr/bin/dot' 替換爲剛查到相應路徑。

在瀏覽器訪問任意一個項目路徑,/tmp/xdebug 目錄下會生成一個 cachegrind.out.xxxxx 文件作爲 webgrind 的數據來源,打開 webgrind 頁面,如:http://localhost/webgrind/, 點擊右上角update 按鈕即會分析最後一次訪問的項目地址的 PHP 程序,可以通過選擇第二個 下拉框中的地址來分析相應的程序,點擊 Show Call Graph 按鈕就會顯示當前分析的程序的 簡明調用流程圖。

表格中後三列的含義:

InvocationCount:函數調用次數TotalSelfCost:函數本身花費的時間TotalInclusiveCost:包含內部函數花費的時間

簡析 webgrind 生成流程圖

webgrind 生成流程圖使用源碼下的 library/gprof2dot.pypython 腳本, 先將cachegrind.out.xxxxx 轉換成 DOT,再使用 dot 命令轉換成圖片輸出。

PHP 使用 shell_exec 函數執行:

/usr/bin/python library/gprof2dot.py -n 10-f callgrind /tmp/xdebug/cachegrind.out.xxxxx |/usr/bin/dot -Tpng-o /tmp/xdebug/cachegrind.out.xxxxx-10.webgrind.png
轉載請註明出處。
本文地址:http://blog.aboutc.net/profiling/18/php-profiler-xdebug-webgrind


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章