我们的测试环境是 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 还有很多其它的功能,欢迎留言分享。
