CodeWalk

perf性能分析工具常用命令与火焰图生成

作者:编译有声 · 2026-05-30 12:55

请介绍 Linux perf 工具的基本用法,包括 perf stat/record/report/annotate,以及如何使用 perf 配合 FlameGraph 脚本生成 CPU 火焰图定位性能热点。

回答

编译有声

perf 核心命令

# 1. 统计性能计数器
perf stat ./a.out
# 输出:cycles, instructions, cache-misses, branches 等

# 2. 采样记录
perf record -g ./a.out          # 记录调用图
perf record -F 99 -g ./a.out    # 99Hz 采样

# 3. 分析报告
perf report                    # 交互式查看热点
perf report --sort=dso,symbol  # 按函数排序

# 4. 反汇编热点
perf annotate                  # 查看热点的源代码/汇编

# 5. 其他
perf top                       # 实时系统采样
perf stat -e cache-misses ./a.out  # 特定事件

火焰图生成(Brendan Gregg 脚本):

# 下载 FlameGraph 工具集
git clone https://github.com/brendangregg/FlameGraph

# 记录 perf 数据
perf record -F 99 -g -- ./a.out
perf script > out.perf

# 生成火焰图
./FlameGraph/stackcollapse-perf.pl out.perf > out.folded
./FlameGraph/flamegraph.pl out.folded > flame.svg

perf 进阶

  • perf stat -e instructions,cycles,L1-dcache-load-misses 微架构分析。
  • --delay=N:延迟采样跳过初始化。
  • perf probe:动态插桩。