|
- gprof工作方式
在使用gcc编译时指定-pg选项,编译器在用户代码中插入性能测试代码。
- gprof简单应用实例
main.c
1
2
3
4
5
6
7
8
9
10
11
| #include <stdio.h>
#include "lib.h"
int main(void)
{
func1(20);
func2(100);
return 0;
}
|
lib.h
1
2
3
4
5
6
7
8
| #ifndef LIB_H
#define LIB_H
void func1(int i);
void func2(int i);
#endif /* LIB_H */
|
lib.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| #include <stdio.h>
#include "lib.h"
void func1(int i)
{
while (i--)
printf("func1(): %d\n", i);
}
void func2(int i)
{
while (i--)
printf("func2(): %d\n", i);
}
|
Makefile
1
2
3
4
5
6
7
8
9
| CFLAGS += -pg
objs = $(patsubst %.c,%.o,$(wildcard *.c))
prog: $(objs)
gcc -pg -o $@ $^
clean:
-rm -f prog $(objs)
|
在命令行运行make编译代码,产生prog文件。输入./prog运行文件,产生一个输出文件gmon.out。之后
用工具gprof分析该输出文件分析程序的运行情况,并依据这些分析得出的数据优化程序。
运行 gprof prog gmon.out > gprofrslt.txt 分析输出文件得到如下结果(节选部分内容)。可根据传递给
gprof不同的参数得出不同方面性能考量的输出。
1
2
3
4
5
6
7
8
9
| 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 1 0.00 0.00 func1
0.00 0.00 0.00 1 0.00 0.00 func2
|
具体输出的含义可参考gprof帮助文档。
3. gprof文档
http://sourceware.org/binutils/docs/gprof/
|
|