最近在擺弄算法的的優化,需要剖分一下算法的瓶頸,就找了一些代碼剖分工具,其中
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\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: 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