gperftools是google出品的一项profiling工具,感觉值得学习一下
cpu profiler
源码示例(https://blog.csdn.net/aganlengzi/article/details/62893533):
void test1() {int i = 0;while (i < 1000) i++;}void test2() {int i = 0;while (i < 2000) i++;}void test3() {for (int i = 0; i < 100000; ++i){test1();test2();}}void foo() {ProfilerStart("test.prof"); // test.prof is the name of profile filetest3();ProfilerStop();}int main() {foo();return 0;}

如果出现上图0的情况,可能是因为执行时间太短了
执行pprof —text,
引用网友的话来解释各列含义:
上面文本中输出的内容是对程序中每一个函数的CPU使用时间分析 总体来看,总共有68个时间样本,每个样本时间是10ms,其中test1和test2分别占了26和42样本时间, 即260ms和420ms. 数据有两大列: 左:不包含内部其他函数调用所消耗的CPU时间(内联函数除外)如果函数内部没有任何调用,那么就和右列相等 右:整个函数消耗的CPU时间,包括函数内部其他函数调用所消耗的CPU时间 每行按照数据顺序: 1 分析样本数量(不包含其他函数调用) 2 分析样本百分比(不包含其他函数调用) 3 目前为止的分析样本百分比(不包含其他函数调用) 4 分析样本数量(包含其他函数调用) 5 分析样本百分比(包含其他函数调用) 6 函数名 ———————————————— 原文链接:https://blog.csdn.net/aganlengzi/article/details/62893533
我对上述例子进行了改造,添加c++的各种函数特性后,有这样的输出:
环境变量指定文件路径
当代码中没有直接调用api时,可用环境变量触发profiling
daemon程序使用信号触发profiling
比如用SIGUSR1启动profiling, 用SIGUSR2停止

使用CPUPROFILESIGNAL来触发
这比使用SIGUSR简单
将prof文件生成pdf
要安装ghostscript, graphviz
pprof —pdf ./program prog.prof > prog.pdf

转成callgrind
pprof —callgrind a.out test.prof > a.out.callgrind
用kcallgrind打开
与perf比较
perf record ./a.out perf report
似乎perf更好些
heap checker
As a quick-start, do the following after installing this package:
1) Link your executable with -ltcmalloc 2) Run your executable with the HEAPCHECK environment var set: $ HEAPCHECK=1
[binary args] Other values for HEAPCHECK: normal (equivalent to “1”), strict, draconian
You can also use LD_PRELOAD to heap-check an executable that you didn’t compile.
The heap checker is only available on Linux at this time; see INSTALL for more details.
要记录每一次分配的stack trace,比较耗内存,也拖慢程序速度;
heap checker与heap profiler不能同时用
tcmalloc
当用gcc编译且用tcmalloc时,最好传-fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free,防止gcc做unexpected优化
heap profiler
1) Link your executable with -ltcmalloc 2) Run your executable with the HEAPPROFILE environment var set: $ HEAPPROFILE=/tmp/heapprof
[binary args] 3) Run pprof to analyze the heap usage $ pprof /tmp/heapprof.0045.heap # run ‘ls’ to see options $ pprof —gv /tmp/heapprof.0045.heap You can also use LD_PRELOAD to heap-profile an executable that you didn’t compile
关于静态链接profiler,tcmalloc到app
不能直接链接它们俩的.a文件,要用libtcmalloc_and_profiler.a
远程使用pprof
https://gperftools.github.io/gperftools/pprof_remote_servers.html
t_use_const_1的例子实战
当在循环中纯调它 1kw次时,耗时208ms
当不用function包装t_use_const_1,而是直接传给utils::repeat_func_call 时,比纯调 1kw次稍微高一点点,228ms; 
当用function对象包住t_use_const_1,并传给utils::repeat_func_call 时,耗时最长,375ms; 采样前三位已和先前大一样,耗在了function内部调用中
最后一种情况,如果用函数指针替换function,再传给utils::repeat_func_call ,性能就和传纯函数一样了。
果然用function包了一层后就有性能损失,下降~ 40%
