gprof

gprof 是什么?

gprof 是一个用来分析应用程序把时间花费在哪的性能分析工具.

gprof 怎么用?

  1. 编译和链接程序使用 -pg 选项;
  2. 执行程序, 产生 gmon.out 数据文件;
  3. 使用 gprof 读取 gmon.out 数据文件产生报告;
//使用 **-pg** 参数编译你的程序
pi@raspberrypi:~ $ echo 'int main(){}' | gcc -o hello -xc -pg -O3 -
pi@raspberrypi:~ $ ls 
hello
pi@raspberrypi:~ $ ./hello
pi@raspberrypi:~ $ ls -lah 
gmon.out  hello

pi@raspberrypi:~ $ which gprof
/usr/bin/gprof

pi@raspberrypi:~ $ gprof hello gmon.out

gprof - how it works?

要想使用 gprof 做性能分析, 必须在编译程序的时候注入一些代码, 这些代码在运行时搜集代码的执行情况, 把搜集的数据放到当前路径下的 gmon.out 文件. 然后 gprof 读这个文件, 生成 report.
实现细节: https://sourceware.org/binutils/docs/gprof/Implementation.html
使用 -pg 选项编译的时候, 每个函数的开头都条用 mcount (monitor count). mcount 在不同的平台实现不同, 不过代码都在 profiling 的 lib 里面, 它负责记录并维护这些 call graph 的数据: 包括当前函数以及谁 call 的当前函数. 一般当前函数以及父函数都是通过遍历栈帧的方式获得的.

The mcount routine, included in the profiling library, is responsible for recording in an in-memory call graph table both its parent routine (the child) and its parent's parent. This is typically done by examining the stack frame to find both the address of the child, and the return address in the original parent. Since this is a very machine-dependant operation, mcount itself is typically a short assembly-language stub routine that extracts the required information, and then calls __mcount_internal (a normal C function) with two arguments - frompc and selfpc. __mcount_internal is responsible for maintaining the in-memory call graph, which records frompc, selfpc, and the number of times each of these call arcs was transversed.

库函数的调用记录是通过特殊的库版本实现的, 通常这些库都是使用-pg选项生成的.

为什么是 pg ?

在 gprof 之前, 有个性能分析程序是 prof, 要使用 prof 这个工具, gcc 给的参数是 -p, 那么轮到 gprof 的时候, 就使用参数 -pg

pg 之外的其它编译参数

-g line-by-line profiling
-a if 的每个分支, loop 的每次循环

refer:
https://hpc.llnl.gov/software/development-environment-software/gprof
https://en.wikipedia.org/wiki/Gprof

标签: none

添加新评论