利用XDebug与KCachegrind进行PHP性能分析

xdebug是php的一个调试工具,但是还有一个功能就是profiler,可以用来分析性能瓶颈(bottleneck)。

引用官方的介绍 http://xdebug.org/docs/profiler:

Xdebug's Profiler is a powerful tool that gives you the ability to analyze your PHP code
and determine bottlenecks or generally see which parts of your code are slow and could use a speed boost.
The profiler in Xdebug 2 outputs profiling information in the form of a cachegrind compatible file.
This allows you to use the excellent KCacheGrind tool (Linux/Windows, KDE) to analyse your profiling data.
If you are on Linux you can install KCacheGrind with your favourite package manager;
if you are on Windows you can get precompiled binaries of KCacheGrind at SourceForge.

在ubuntu中用命令安装php的xdebug扩展:

sudo apt-get install php5-xdebug

安装完后,需要在php.ini中配置一下xdebug参数,在 ubuntu 中就是 /etc/php5/conf.d/xdebug.ini:

zend_extension=/usr/lib/php5/20090626/xdebug.so
; profiler settings
xdebug.profiler_append=1
xdebug.profiler_enable=0                               #默认不开启profile功能,由下面的trigger参数设置成由参数来触发
xdebug.profiler_enable_trigger=1
xdebug.profiler_output_name=cachegrind.out.%s.%H       #输出profiler文件的命名规则
xdebug.profiler_output_dir="/home/chenming/xdebug/"    #输出profiler文件的位置,要有可读写权限
xdebug.trace_output_dir="/home/chenming/xdebug/"
xdebug.remote_enable=true
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
xdebug.remote_handler=dbgp

我们上面设置的profiler_enable_trigger参数,表示通过XDEBUG_PROFILE这个GET或POST参数手动来触发proflile功能。
在chrome里面有个方便的插件,xdebug helper,可以很方便地开启xdebug的各种功能。

上图中的时钟一样的小图标,就表示开启profile。
运行后就会在我们设置的目录里面生成一个out文件:cachegrind.out._home_chenming_www_weborbit_coreHander_php.localhost

这时候光有这个文件看不出什么名堂。我们需要一个将数据可视化的工具:KCachegrind

在ubuntu中通过下面命令来安装KCachegrind:

sudo apt-get install kcachegrind

安装好后启动,打开我们刚生成的out文件,就有了可视化界面:

对界面的一些说明。左边的函数列表中,列出了调用过的每个函数,其中php内置函数用php::标识出来了的。其中self栏表未该函数自身花费了多少时间(百分比),called表示总共被调用了多少次。
右边的图表,上半部表示当前函数调用了哪些子函数,和个子函数花费的时间比例是怎样的。下半部表示调用层次结构图。
在最下面的状态栏中,有显示当前执行总共用了多少时间。

另外KCachegrind这个工具不仅仅是针对php的哦,其它像c、c++、python等都可以用它来进行性能分析,内存泄露分析等。
比如,

http://stackoverflow.com/questions/1896032/using-cprofile-results-with-kcachegrind

这里就有讨论python。
这里,

http://blog.dccmx.com/2011/01/callgrind/

就有讨论C的。