Linux性能优化工具:gprof简记

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文档

gprof官方文档

6. 后记

本篇移自个人51CTO博客原地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值