Xdebug + Webgrind/KCacheGrind 属于 函数级别的性能分析(Profiler),能看到“一个 URL 执行了哪些 PHP 函数、每个函数耗时多少、调用次数”。
1. 安装 Xdebug
首先确认 PHP 版本(例:php -v)。
安装 Xdebug:
# Ubuntu/Debian
sudo apt-get install php8.4-xdebug
# 或者源码安装
pecl install xdebug
查看是否成功:
php-fpm8.4 -m | grep xdebug
2. 配置 Xdebug Profiler
编辑 php.ini 或者 FPM 配置(/etc/php/8.x/fpm/conf.d/20-xdebug.ini):
zend_extension=xdebug.so
; 启用 profiler
xdebug.mode=profile
xdebug.start_with_request=yes ; 每次请求都记录(建议只在调试环境开)
; 输出目录
xdebug.output_dir="/tmp/xdebug"
; 控制文件名(方便识别请求)
xdebug.profiler_output_name=cachegrind.out.%R
; 禁用压缩
xdebug.use_compression = 0
创建输出目录,并设置权限
mkdir /tmp/xdebug;
sudo chown www-data:www-data /tmp/xdebug;
sudo chmod 777 /tmp/xdebug;
重启 PHP-FPM 和 Nginx:
sudo service php8.4-fpm restart
sudo service nginx restart
3. 触发请求,生成 profile 文件
访问一个 WordPress 页面(比如 /shop/product/123),
然后到 /tmp/xdebug/ 查看:
ls -lh /tmp/xdebug/
# cachegrind.out.12345-localhost%2Fshop%2Fproduct%2F123
这个文件就是 函数级调用记录。
4. 分析 profile 文件
方法 A:KCacheGrind(Linux 桌面)
sudo apt-get install kcachegrind
kcachegrind /tmp/xdebug/cachegrind.out.12345*
你会看到:
- 调用图(调用关系)
- 每个函数耗时(CPU/Wall Time)
- 调用次数
方法 B:Webgrind(Web UI)
浏览器访问 http://yourserver/webgrind/ → 选择 profile 文件查看。
下载 Webgrind:
git clone https://github.com/jokkedk/webgrind.git /var/www/webgrind
配置 Nginx 虚拟主机,指向 /var/www/webgrind。
(/var/www/webgrind目录需要给读写权限)
生成图形化调用图,需要安装jrfonseca/gprof2dot,
安装graphviz
apt-get install python3 graphviz
安装gprof2dot
pip3 install gprof2dot
详见:https://github.com/jrfonseca/gprof2dot
Webgrind中查看其他vhost的文件代码,需要在config.php配置中修改成:
static function exposeServerFile($file) {
// return false; // Deny all access.
return $file; // Grant access to all files on server.
}
5. 常见调试流程
比如你访问 /shop/product/123,在 Webgrind/KCacheGrind 里可以看到:
- 入口函数:
wp()→WP_Query->get_posts()→WC_Product_Factory->get_product() - 发现
get_post_meta()调用 500 次,耗时最多。 - 就能判断:某个插件反复查询 meta,应该用缓存优化。
6. 注意事项
- 生产环境不要长期开 Xdebug:性能损耗很大(10~30%)。
- 推荐只在本地/测试环境开启,或者设置:
xdebug.start_with_request=trigger然后通过 URL 参数触发:https://example.com/?XDEBUG_TRIGGER=1 - 文件清理:
/tmp/xdebug会积累很多cachegrind文件,注意定期清理。