文档和结果分析在官网上都有 http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html
1.下载安装google-perftools
2.在需要分析的程序块前后加上初始化和结束的语句
ProfilerStart("CPUProfile");
ProfilerStop();
3.编译和运行
g++ perftools_test.cpp -o perftooles_test -lprofiler -I/usr/local/include/google
./perftools_test
4.把运行结果CPUProfile转化成pdf格式的文件
pprof --pdf ./perftools_test CPUProfile > tt.pdf
PS:本人工作中用perftools分析一个使用了CLucene、jsonc等外援的程序性能,无意中发现程序会在jsonc拼串的地方宕机,注释掉jsonc拼串的代码块就正常,貌似存在冲突
下面贴上一个demo程序
#include<stdio.h>
#include<profiler.h>
void consumeSomeCPUTime1(int input){
int i = 0;
input++;
while(i++ < 10000){
i--; i++; i--; i++;
}
};
void consumeSomeCPUTime2(int input){
input++;
consumeSomeCPUTime1(input);
int i = 0;
while(i++ < 10000){
i--; i++; i--; i++;
}
};
int stupidComputing(int a, int b){
int i = 0;
while( i++ < 10000){
consumeSomeCPUTime1(i);
}
int j = 0;
while(j++ < 5000){
consumeSomeCPUTime2(j);
}
return a+b;
};
int smartComputing(int a, int b){
return a+b;
};
int main(){
int i = 0;
printf("reached the start point of performance bottle neck\n");
//sleep(5);
ProfilerStart("CPUProfile");
while( i++ < 10){
printf("Stupid computing return : %d\n",stupidComputing(i, i+1));
printf("Smart computing return %d\n",smartComputing(i+1, i+2));
}
printf("should teminate profiling now.\n");
//sleep(5);
ProfilerStop();
}