本文目录导读:

- 方式一:使用 Xdebug + 可视化工具(最简单)
- 方式二:使用 XHProf + 火焰图生成器(推荐)
- 方式三:使用 Tideways + Docker(生产环境友好)
- 快速上手示例(方式二全套)
- 可视化查看
- 推荐的第三方工具
PHP 生成火焰图主要有两种方式,我来分别介绍:
使用 Xdebug + 可视化工具(最简单)
配置 Xdebug
# php.ini xdebug.mode=profile xdebug.output_dir=/tmp/xdebug xdebug.profiler_output_name=cachegrind.out.%t.%p
运行你的 PHP 脚本
# 命令行方式 php -dxdebug.mode=profile -dxdebug.output_dir=/tmp/xdebug your_script.php
生成火焰图
# 安装工具 (macOS) brew install flamegraph # 转换 Xdebug 输出为火焰图 # 先转换为 callgrind 格式 qcachegrind /tmp/xdebug/cachegrind.out.* # 或者使用 PHP 工具直接转换 composer require --dev bvanhoekelen/php-flamegraph
使用 XHProf + 火焰图生成器(推荐)
安装 XHProf
# Ubuntu/Debian apt-get install php-xhprof # 或通过 PECL pecl install xhprof
创建配置文件
// xhprof_config.php
<?php
// 启用 XHProf
xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
// 注册 shutdown 函数来保存数据
register_shutdown_function(function() {
$data = xhprof_disable();
// 保存数据
$filename = '/tmp/xhprof_' . uniqid() . '.xhprof';
file_put_contents($filename, serialize($data));
});
生成火焰图脚本
#!/bin/bash
# generate_flamegraph.sh
# 1. 收集到的 XHProf 数据转换为火焰图格式
php -r '
$data = unserialize(file_get_contents($argv[1]));
$output = [];
foreach ($data as $call => $metrics) {
[$from, $to] = explode("==>", $call);
$output[] = implode(";", [$from, $to]) . " " . $metrics["wt"];
}
file_put_contents($argv[2], implode("\n", $output));
' $1 $2
# 2. 生成火焰图
./flamegraph.pl $2 > flamegraph.svg
使用 Tideways + Docker(生产环境友好)
使用 Docker 镜像
FROM php:8.1-cli
RUN apt-get update && apt-get install -y git
# 安装 tideways
RUN pecl install tideways && \
docker-php-ext-enable tideways
集成到代码
<?php // 在脚本开始处 Tideways\Profiler::start(); Tideways\Profiler::setEnabled(true); // 业务代码... // 脚本结束处 Tideways\Profiler::stop();
快速上手示例(方式二全套)
<?php
// profile.php - 使用 XHProf 生成火焰图数据
// 启用 profiler
xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
// 你的业务代码
function testFunction() {
for ($i = 0; $i < 10000; $i++) {
$arr[] = $i;
}
sleep(1);
}
testFunction();
// 禁用并获取数据
$data = xhprof_disable();
// 转换格式并保存
$output = [];
foreach ($data as $call => $metrics) {
[$from, $to] = explode("==>", $call, 2);
$output[] = ($from === "" ? "main" : $from) . ";" . ($to ?? "end") . " " . $metrics["wt"];
}
file_put_contents('/tmp/flame_data.txt', implode("\n", $output));
// 使用命令行生成火焰图
// cat /tmp/flame_data.txt | ./flamegraph.pl > flamegraph.svg
可视化查看
生成 SVG 文件后,直接在浏览器中打开即可查看:
# 生成火焰图 cat /tmp/flame_data.txt | flamegraph.pl > flamegraph.svg # 打开 open flamegraph.svg # macOS xdg-open flamegraph.svg # Linux
推荐的第三方工具
- PHP Flamegraph:https://github.com/brendangregg/FlameGraph
- XHGui:更强大的 PHP 性能分析工具
- Blackfire.io:商业 PHP 性能分析工具
选择哪种方式取决于你的场景:
- 本地调试:Xdebug 最简单
- 生产环境:XHProf 或 Tideways 更适合
- 需要详细分析:使用 XHGui 这类完整工具