最近在摆弄算法的的优化,需要剖分一下算法的瓶颈,就找了一些代码剖分工具,其中
gprofileer-tools是很不错的工具,gperftools时google开源的一款C++性能分析分析工具,github项目地址如下:
一 下载和安装:
1.git clone:
2 . 安装:
根目录下执行:sh autogen.sh
然后执行:./configure
最后:make all && sudo make install
安装成功。
如果没有安装libunwind会出现如,configure执行后报警告:
configure: WARNING: No frame pointers and no libunwind. Using experimental backtrace capturing via libgcc. Expect crashy cpu profiler.
解决方法:
使用命令apt-get install libunwind8-dev安装libunwind即可。
3 最后使用ldconfig更新一下库文件即可。
二 使用和实例:
1 使用gprofiler-tools需要在的代码中添加如下几段代码:
A头文件:
#include
B 起止函数:
修改程序的源代码使得要profiler的代码段包含在ProfilerStart("name");和ProfilerStop();
C链接文件添加需要链接的宏:
lprofiler //cpu性能
-ltcmalloc //heap资源
2 实例:
#include #include#include#include#include
void consumeSomeCPUTime1(intinput){int i = 0;
input++;while(i++ < 10000){
i--; i++; i--; i++;
}
};void consumeSomeCPUTime2(intinput){
input++;
consumeSomeCPUTime1(input);int i = 0;while(i++ < 10000){
i--; i++; i--; i++;
}
};int stupidComputing(int a, intb){int i = 0;while( i++ < 10000){
consumeSomeCPUTime1(i);
}int j = 0;while(j++ < 5000){
consumeSomeCPUTime2(j);
}return a+b;
};int smartComputing(int a, intb){return a+b;
};intmain()
{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");
ProfilerStop();
sleep(5);return 0;
}
编译运行:
gcc -g test.c -o prog -lprofiler
export CPUPROFILE=info.prof
执行:
pprof -text prog info.prof
结果:
Using local file prog.
Using local file info.prof.
Total:1348samples1017 75.4% 75.4% 1017 75.4%consumeSomeCPUTime1331 24.6% 100.0% 674 50.0%consumeSomeCPUTime20 0.0% 100.0% 1348 100.0%__libc_start_main0 0.0% 100.0% 1348 100.0%_start0 0.0% 100.0% 1348 100.0%main0 0.0% 100.0% 1348 100.0% stupidComputing
报错一:
解决方法:
sudo /sbin/ldconfig
错误二:
Using local file prog.
Use of uninitialized value $host in substitution (s///) at /usr/local/bin/pprof line 3366.
Use of uninitialized value $hostport in concatenation (.) or string at /usr/local/bin/pprof line 3368.
Use of uninitialized value $prefix in concatenation (.) or string at /usr/local/bin/pprof line 3368.
Use of uninitialized value $host in substitution (s///) at /usr/local/bin/pprof line 3366.
解决方法:
env CPUPROFILE=/tmp/mybin.prof /home/gprofiler-tools/prog
参考资料: