0%

gnu代码分析工具

gcov

gcov 是 GNU 中的代码覆盖率测试工具,随着 GCC 版本发布,可以实现对 C/C++ 文件中代码和分支覆盖测试。具体包括下面的信息:

  • 统计每行代码的执行频率
  • 实际执行了哪些代码
  • 每段代码的执行时间

使用 gcov 分析代码前,需要添加编译选项 ‘–coverage’,编译会生成源码对应的 gcno 文件。

1
2
3
$ gcc test.c --coverage
$ ls
a.out test.c test.gcno

执行可执行文件,会生成对应的 gcda 文件。

1
2
3
$ a./out
$ ls
a.out test.c test.gcda test.gcno

运行 gcov,生成对应的 gcov 文件。

1
2
3
4
5
6
7
8
9
10
11
$ gcov test.c
File 'test.c'
Lines executed:100.00% of 7
Creating 'test.c.gcov'

File '<built-in>'
No executable lines
Removing '<built-in>.gcov'

$ ls
a.out test.c test.c.gcov test.gcda test.gcno

test.c.gcov 文件中统计了每行代码执行的次数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
     -:    0:Source:test.c
-: 0:Graph:test.gcno
-: 0:Data:test.gcda
-: 0:Runs:1
-: 0:Programs:1
-: 1:#include <stdio.h>
-: 2:
100000: 3:void test(int i) {
100000: 4: if (i % 4 == 0)
25000: 5: printf("%d\n", i);
100000: 6:}
-: 7:
-: 8:
1: 9:int main(int argc, char **argv) {
100001: 10: for (int i = 0; i < 100000; i++) {
100000: 11: test(i);
-: 12: }
-: 13:}

gprof

结合 gprof 工具,能够看出函数之间的调用关系及执行的时间,完成代码优化。

使用 gprof,需要添加编译选项 ‘-pg’ 进行编译

1
2
3
$ gcc test.c -pg
$ ls
a.out test.c

执行可执行文件,生成对应的 gmon.out 文件。

1
2
3
$ ./a.out
$ ls
a.out gmon.out test.c

运行 gprof,显示详细的函数调用信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$ gprof -b a.out
Flat profile:

Each sample counts as 0.01 seconds.
no time accumulated

% cumulative self self total
time seconds seconds calls Ts/call Ts/call name
0.00 0.00 0.00 100000 0.00 0.00 test


Call graph


granularity: each sample hit covers 2 byte(s) no time propagated

index % time self children called name
0.00 0.00 100000/100000 main [7]
[1] 0.0 0.00 0.00 100000 test [1]
-----------------------------------------------


Index by function name

[1] test