gprof工作方式
在使用gcc编译时指定-pg选项,编译器在用户代码中插入性能测试代码。
gprof简单应用实例
main.c
#include <stdio.h>
#include "lib.h"
int main(void)
{
func1(20);
func2(100);
return 0;
}
lib.h
#ifndef LIB_H
#define LIB_H
void func1(int i);
void func2(int i);
#endif /* LIB_H */
lib.c
#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
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不同的参数得出不同方面性能考量的输出。
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. grof缺点
对多线程、内核态支持不好。只统计占用的CPU时间,而陷入睡眠态的时间不做统计,可结合time命令等
其他工具来优化性能。
4. gprof文档
转载于:https://blog.51cto.com/4594296/1841733