gprof是程序性能分析的一个重要工具,通过gprof工具可以获取程序中函数之间的调用关系,每个函数的调用次数,及函数的消耗时间,从而为程序性能优化指明方向。由此也可以推断出,一个合理的程序设计是相当重要的,很难想象,一个结构杂乱,耦合严重的程序如何进行优化。gprof工具的使用非常简单,下面将对该工具进行简单的介绍。
环境:centos7.2,gcc 4.8.5
源码gprof_example.c(为了方便说明gprof分析结果各列关系,加入了循环计算,增加函数执行时间,否则多数列结果均为0.00)如下:
/*
* @file gprof_example.c
* @brief 统计/etc/autofs.conf中单词auto的数量,并打印其所在的行
*/
#include <string.h>
#include <stdio.h>
/*
* @func PrintLine
* @brief 打印auto所在的行,及行号
* @param[in] num 行号
* @param[in] txt 内容
* @return 无
*/
void PrintLine(int num, char *txt)
{
int i = 0;
double b = 3.14;
if (txt != NULL)
printf("%d : %s\n", num, txt);
for (; i < 500000; ++i)
b += b * i;
}
/*
* @func SearchWord
* @brief 判断文本中是否含有某个单词
* @param[in] txt 文本内容
* @param[in] word 待查找的单词
* @return 如果找到单词,返回1,否则返回0
*/
int SearchWord(char *txt, char *word)
{
char *pos = NULL;
int i = 0;
double b = 3.14;
if (txt == NULL || word == NULL)
return 0;
for (; i < 100000; i++)
b += b * i;
pos = strstr(txt, word);
return (pos == NULL ? 0 : 1);
}
/*
* @func StatisticsWord
* @brief 统计文本文件中某个单词的频度,并输出相关内容
* @param[in] file 文件名
* @param[in] word 待统计的单词
* return 单词的频度
*/
int StatisticsWord(char *file, char *word)
{
int count = 0;
char buffer[8192];
int line = 0;
FILE *pf = NULL;
if (file == NULL || word == NULL)
return 0;
pf = fopen(file, "r");
if (pf != NULL) {
while(fgets(buffer, 8192, pf) != NULL) {
if (SearchWord(buffer, word) == 1) {
PrintLine(line, buffer);
count += 1;
}
line += 1;
}
}
return count;
}
int main(int argc, char **argv)
{
StatisticsWord("/etc/autofs.conf", "auto");
return 0;
}
工具的使用步骤:
1.执行gcc -pg -o gprof_example gprof_example.c生成可执行程序
2.执行./gprof_example 生成gmon.out文件,该文件供gprof分析使用
3.执行gprof -b ./gprof_example > profile.txt,将结果输入到profile.txt
之所以把结果写入文件,是为了方便分析。使用vim打开profile.txt便可以看到分析结果:
结果分为两部分,第一部分为函数调用信息,第二部分为函数调用关系。
函数调用信息表说明:
序号 | 名称 | 说明 |
0 | % time | 该函数执行时间占整个程序执行时间的百分比,尽管PrintLine的单次执行时间长于SearchWord,但执行次数要远小于后者 |
1 | cumulative seconds | 执行该函数和前面函数消耗的总时间,该时间为执行SearchWord消耗的总时间+执行PrintLine消耗的总时间 |
2 | self seconds | 执行该函数消耗的总时间(calls * self ms/call) |
3 | calls | 被调用次数 |
4 | self ms/call | 函数单次执行时间,不包括调用其他函数的时间,因为 StatisticsWord比较简单,所以其执行时间很短,几乎为0ms |
5 | total ms/call | 函数总执行时间,该时间包括调用其他函数的时间,如 StatisticsWord执行时间包括调用SearchWord,PrintLine等函数的执行时间;SearchWord,PrintLine没有调用其他函数,所以self和total两列时间相等。 |
6 | name | 函数名称 |
使用gprof工具需要注意以下几个问题:
1.cpu计时不是很准确
2.假设没有执行内联替换,则调用信息相当可靠
3.默认情况下,不会显示对库函数的计时,库函数的计时都被计算到调用它们的函数的时间中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)