1. 前言
限于作者能力水平,本文可能存在谬误,因此而给读者带来的损失,作者不做任何承诺。
2. gprof工作基本原理
在使用gcc
编译时指定-pg
选项,编译器在用户代码中插入性能测试代码。
3. 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 > gprof-result.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
4 gprof缺点
对多线程、内核态支持不好。只统计占用的CPU时间,而陷入睡眠态的时间不做统计,可结合time
命令等其他工具来优化性能。
5. gprof文档
6. 后记
本篇移自个人51CTO博客原地址