callgrind和kcachegrind查看调用时间和调用图

callgrind

callgrind 是 valgrind 套件中的一个工具,使用方式为

1
valgrind --tool=callgrind ./your_program your_program_args1 your_program_args2

运行之后,可以生成一份 callgrind.out.pid 的文件,在当前目录下。这份文件记录了运行时的一些数据,以及函数调用关系。

kcachegrind

kcachegrind 可以分析上述产生的 callgrind.out.pid 的文件,并且点击下方 call graph 可以看到调用关系图,帮助我们分析代码结构。

点击下载windows版kcachegrind

示例

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int accumulate(int begin, int end) {
int result = 0;
for (int i = begin; i < end; i++) {
result += i;
}
}

int accumulate0_100000() {
return accumulate(0, 100000);
}

int accumulate0_200000() {
return accumulate(0, 200000);
}

int main() {
accumulate0_100000();
accumulate0_200000();
return 0;
}
1
valgrind --tool=callgrind --dump-instr=yes --trace-jump=yes ./a.out

kcachegrind分析

生成文件后,使用 kcachegrind 工具打开这个分析文件。

1

可以从图中看到函数执行时间,百分比等功能。

gprof2dot分析

使用 gprof2dot 工具,需要安装 python 和 graphviz。

1
2
yum install graphviz
pip3 install gprof2dot

之后使用上述工具对其进行分析,生成调用图。

1
2
gprof2dot -f callgrind -n0 -e0 ./callgrind.out.2328 > callgrind.2328.dot
dot callgrind.2328.dot -Tsvg -o callgrind.2328.dot.svg

其中 -f 指定输出格式为 callgrin d格式,-nX 指定生成的文件忽略小于 X 个 node 的函数,例如 -n10,代表函数节点小于 10 个的,在最终文件中不生成其相关信息,-eX 代表边缘阈值,与 -n 类似。