gprof 性能分析工具

gprof 是 GNU 性能分析工具(GNU Profiler),用于分析程序的 时间消耗分布函数调用关系。它通过统计采样和调用图(Call Graph)帮助开发者定位性能瓶颈。以下是详细使用指南:


使用步骤

1. 编译时启用 profiling

gcc/g++ 编译时添加 -pg 选项:

gcc -pg -o my_program my_program.c   # C 程序
g++ -pg -o my_program my_program.cpp # C++ 程序

cmake -DCMAKE_CXX_FLAGS="-pg" .. # cmake 下
make
  • 关键要求:必须包含调试符号(不推荐同时使用 -O3,高优化可能干扰分析结果)。

2. 运行程序生成数据

./my_program [参数]
  • 程序正常退出(不能 kill -9 强制终止)后,会生成 gmon.out 文件。

3. 生成分析报告

gprof my_program gmon.out > report.txt

报告解读

输出报告包含两部分:

1. Flat Profile(平面性能分析)

按函数统计时间消耗,关键列:

列名 说明
% time 函数消耗时间占比
cumulative seconds 累积时间(包含子函数)
self seconds 函数自身消耗时间(不含子函数)
calls 调用次数
self ms/call 每次调用自身耗时(毫秒)
name 函数名

示例输出

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total           
 time   seconds   seconds    calls  ms/call  ms/call  name    
 33.34      0.02     0.02     1000     0.02     0.02  func1
 16.67      0.03     0.01     2000     0.01     0.01  func2

2. Call Graph(调用图)

展示函数调用关系,关键字段:

  • index: 函数索引号(用于追踪调用链)
  • calls: 调用次数
  • self: 函数自身耗时
  • children: 子函数累积耗时
  • name: 函数名及调用者(<spontaneous> 表示栈底函数,如 main

示例输出

index % time    self  children called     name
                0.01    0.02   100/1000       func1 [2]
[1]     50.0    0.01    0.02   100         main [1]
                0.01    0.00   200/2000       func2 [3]
-----------------------------------------------
[2]     33.3    0.02    0.00  1000        func1 [2]

高级技巧

1. 只关注特定函数

gprof -p function_name my_program gmon.out   # 分析单个函数
gprof -Pfoo -Qbar my_program gmon.out        # 排除/包含特定函数

2. 生成调用图图片

  1. 生成 Graphviz 格式的调用图:
    gprof my_program | gprof2dot -s -w | dot -Tpng -o call_graph.png
    
    (需要安装 gprof2dotgraphviz

3. 结合优化选项

若需分析优化后的代码:

gcc -pg -O2 -o my_program my_program.c  # 允许O2优化

注意:激进优化(如 -O3)可能导致函数内联,影响统计准确性。


局限性

  1. 采样误差:基于定时器中断(约10ms采样一次),短函数(<10ms)可能无法统计。
  2. 多线程支持弱:对多线程程序分析不准确(建议改用 perfvtune)。
  3. 内核时间不统计:只记录用户态 CPU 时间(I/O 等待时间不计入)。

替代工具推荐

  • perf:Linux 内核级分析(支持硬件计数器)。
  • Valgrind/callgrind:精确插桩分析(支持缓存命中率统计)。
  • GCOV:代码覆盖率分析(与 gprof 互补)。

通过 gprof 可快速定位热点函数,是优化程序性能的首选入门工具。

posted @ 2025-06-23 11:15  BlackSnow  阅读(522)  评论(0)    收藏  举报