最近在摆弄算法的的优化,需要剖分一下算法的瓶颈,就找了一些代码剖分工具,其中
gprofileer-tools是很不错的工具,gperftools时google开源的一款C++性能分析分析工具,github项目地址如下:
https://github.com/gperftools/gperftools
一 下载和安装:
1.git clone:
git clone https://github.com/gperftools/gperftools
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 <gperftools/profiler.h>
B 起止函数:
修改程序的源代码使得要profiler的代码段包含在ProfilerStart("name");
和ProfilerStop();
C链接文件添加需要链接的宏:
lprofiler //cpu性能
-ltcmalloc //heap资源
2 实例:
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <gperftools/profiler.h> #include <unistd.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 "); sleep(5); ProfilerStart("CPUProfile"); while( i++ < 10){ printf("Stupid computing return : %d ",stupidComputing(i, i+1)); printf("Smart computing return %d ",smartComputing(i+1, i+2)); } printf("should teminate profiling now. "); 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: 1348 samples 1017 75.4% 75.4% 1017 75.4% consumeSomeCPUTime1 331 24.6% 100.0% 674 50.0% consumeSomeCPUTime2 0 0.0% 100.0% 1348 100.0% __libc_start_main 0 0.0% 100.0% 1348 100.0% _start 0 0.0% 100.0% 1348 100.0% main 0 0.0% 100.0% 1348 100.0% stupidComputing
报错一:
Google perftool cannot read file “libprofiler.so.0”
解决方法:
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
参考资料:
1 https://www.kancloud.cn/subin/blog/619133
2 https://github.com/gperftools/gperftools
3 https://stackoverflow.com/questions/1581494/google-perftool-cannot-read-file-libprofiler-so-0
4 https://www.ibm.com/developerworks/cn/linux/l-cn-googleperf/index.html