使用gperftools分析
配置环境
perftools:http://code.google.com/p/gperftools/downloads/list
libunwind:http://download.savannah.gnu.org/releases/libunwind/
64位操作系统需要安装libunwind,官方推荐版本是libunwind-0.99-beta
安装过程:
./configure
make
make install
配置环境变量
export LD_LIBRARY_PATH=/usr/local/lib
Demo
test.cc
#include <gperftools/profiler.h>
#include <stdlib.h>
void f() {
int i;
for (i = 0; i < 1024 * 1024; ++i) {
char *p = (char *)malloc(1024 * 1024 * 120);
free(p);
}
}
void fun1() { f(); }
void fun2() { f(); }
int main() {
fun1();
fun2();
return 0;
}
在编译的时候连接libprofiler和libunwind
g++ test.cc -o test -lprofiler -lunwind
配置要分析的可执行程序,生成profile
CPUPROFILE=./profile ./test
生成文本格式的测试报告:
pprof --text ./test profile > profile.txt
对于一个函数的CPU使用时间分析,分为两个部分:
- 整个函数消耗的CPU时间,包括函数内部其他函数调用所消耗的CPU时间
- 不包含内部其他函数调用所消耗的CPU时间(内联函数除外)
关于文本风格输出结果:
序号 |
说明 |
1 |
分析样本数量(不包含其他函数调用) |
2 |
分析样本百分比(不包含其他函数调用) |
3 |
目前为止的分析样本百分比(不包含其他函数调用) |
4 |
分析样本数量(包含其他函数调用) |
5 |
分析样本百分比(包含其他函数调用) |
6 |
函数名 |
Total: 690 samples
384 55.7% 55.7% 384 55.7% __munmap
219 31.7% 87.4% 274 39.7% sysmalloc
55 8.0% 95.4% 55 8.0% __mmap64
17 2.5% 97.8% 297 43.0% __GI___libc_malloc
9 1.3% 99.1% 682 98.8% f
6 0.9% 100.0% 280 40.6% _int_malloc
0 0.0% 100.0% 690 100.0% __libc_start_main
0 0.0% 100.0% 690 100.0% _start
0 0.0% 100.0% 358 51.9% fun1
0 0.0% 100.0% 332 48.1% fun2
0 0.0% 100.0% 690 100.0% main