1、依赖库
autoconf
automake
libtool
libunwind
1、1安装libunwind
获取libunwind,可以从github 官方地址获取相关版本,此处版本使用v1.8.0.tar.gz
tar -xvf v1.8.0.tar.gz
cd libunwind-1.8.0
# Needed only for building from git. Depends on libtool.
autoreconf -i
./configure --prefix=/usr/local
make
make install
2、安装gperftools
获取gperftools 版本,此处采用gperftools-2.15
tar -xvf gperftools-2.15
cd gperftools-gperf-tools-2.15
./autogen.sh
./configure
make
make install
3、使用方法
1、直接调用api。此种方法对程序的某个局部进行分析。
方式:调用 ProfilerStart() 和 ProfilerStop(),此方法需要包含头文件
#include <gperftools/profiler.h>
此方式需要在代码编译过程中指定链接库:-lprofiler -lunwind
2、链接静态库。此方法常用
方式:在代码link过程中添加参数 -lprofiler
CPUPROFILE=/tmp/profile ./cpu_profiler_example
3、动态链接库。类似静态库方法.(通常不推荐)
方式: 运行时使用LD_PRELOAD
3.1 数据分析
使用 pprof 进行数据分析
3.2 分析技巧
以txt 方式查看报告
pprof --text ./test test_capture.prof > prof.txt
以web 的方式查看报告
pprof ./test test_capture.prof -web
以pdf方式查看报告
pprof ./test test_capture.prof -pdf > prof.pdf
使用性能分析工具Analuzing Callgrind 查看报告
pprof --callgrind ./test test_capture.prof > test.callgrind
kcachegrind test.callgrind
专注与忽视
如果程序函数较多,只想关注某个函数的调用关系,可以加上--focus ,比如只想关注 a 函数 相关的调用关系,可以加上 --focus=a;如果不想关注关注某个函数可以加上 --ignore=a。
pprof --gv --focus=a test test.prof
4、测试例子
#include <stdio.h>
#include <stdlib.h>
#include <gperftools/profiler.h>
int loop(){
int count = 500000000;
int i = 0;
for(i = 0; i < count; i++){
double res = i % 100 + i / 100;
}
return 0;
}
int main(){
ProfilerStart("test_capture.prof");
loop();
ProfilerStop();
}