用gperftools对C/C++程序进行profile

2021-04-30  本文已影响0人  Aska偶阵雨

下载

google-perftools: https://github.com/gperftools/gperftools

libunwind:http://download.savannah.gnu.org/releases/libunwind/libunwind-1.1.tar.gz

解压安装

tar -zxvf gperftools-2.5.tar.gz

./configure && make -j8 && make install

64位操作系统请先安装 libunwind库,32位操作系统不要安装。libunwind库为基于64位CPU和操作系统的程序提供了主要的堆栈辗转开解功能。当中包含用于输出堆栈跟踪的API、用于以编程方式辗转开解堆栈的API以及支持C++异常处理机制的API。

tar zxvf libunwind-1.1.tar.gz

./configure && make -j8 && make install

TCMalloc库载入到Linux系统中

echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf

/sbin/ldconfig

编译程序

g++ -o test_profile test_profile.cpp -lprofiler -ltcmalloc

注意这里为了进行内存泄漏分析,一定要将TCMalloc链接在最后,官方文档里说:堆栈检查器可能误解列在它后面的链接库的一些内存。

运行程序

CPU:CPUPROFILE=cpu.prof ./test_profile

MEM:HEAPPROFILE=heap.prof ./test_profile

LEAKCHECK:HEAPCHECK=normal ./test_profile

查看分析结果

依赖工具安装 yum install graphviz && yum install ghostscript

文本方式 pprof -text ./test_profile cpu.prof

图片方式 pprof -pdf ./test_profile cpu.prof > out.pdf

Res方式 pprof --callgrind ./test_profile cpu.prof > out.res

然后利用kcachegrind打开这个out.res文件就可以看到类似下面的画面(图片来自kcachegrind官网):

image.png

kcachegrind下载

https://nchc.dl.sourceforge.net/project/qcachegrindwin/0.7.4/qcachegrind074-32bit-x86.zip

动态profile

#include <gperftools/profiler.h>
int main()
{
    ProfilerStart("/tmp/profile");
    some_func_to_profile();
    ProfilerStop();
    return 0;
}

在想要profile的函数的开头和结尾加上ProfilerStart和ProfilerStop调用就可以了。

性能损耗

gperftools的profile过程采用的是采样的方式,而且对profile中的程序性能影响极小, 这对于在线或者离线profile都是一个极其重要的特点。

上一篇下一篇

猜你喜欢

热点阅读