gperftools之heap checker使用小结

0.背景

gperftools是google开发的一款非常实用的工具集,主要包括:性能优异的malloc free内存分配器tcmalloc;基于tcmalloc的堆内存检测和内存泄漏分析工具heap-profiler,heap-checker;基于tcmalloc实现的程序CPU性能监测工具cpu-profiler.

github地址
上述所说的三种工具在我们服务器进程的性能分析监控,定位内存泄漏,寻找性能热点,提高malloc free内存分配性能的各个方面上都有非常成功的使用经验.

1. 编译安装

参考文章:gperftools之cpu-profiler使用小结 第1章

2. 使用

2.1 编译

官方文档: Gperftools CPU Profiler
编译时设置编译选项 -ltcmalloc ,添加链接目录 /usr/local/lib .
cmake 添加如下代码会链接动态库

# gperftools
if(CMAKE_GPERF_TOOLS)
 set(CMAKE_CXX_FLAGS "-ltcmalloc ${CMAKE_CXX_FLAGS}")
 link_directories("/usr/local/lib")
 message("-ltcmalloc")
endif() 

通过如下代码链接静态库

# gperftools
if(CMAKE_GPERF_TOOLS)
 target_link_libraries(test_tools libtcmalloc.a)
endif()

2.2 运行

HEAPPROFILE=/tmp/profile PPROF_PATH=/usr/local/bin/pprof HEAPCHECK=normal ./application
强杀进程会使工具失效,程序需要正常退出才会打印出相应的内存泄露信息。HEAPCHECK有四个等级minimal,normal,strick,draconian。一般来说normal能满足绝大部分使用场景了。下面是官方文档中关于四个等级的介绍

"Normal" heap-checking tracks live objects and reports a leak for any data that is not reachable via a live object when the program exits.

"Strict" heap-checking is much like "normal" but has a few extra checks that memory isn't lost in global destructors. In particular, if you have a global > > > variable that allocates memory during program execution, and then "forgets" about the memory in the global destructor (say, by setting the pointer to it to > NULL) without freeing it, that will prompt a leak message in "strict" mode, though not in "normal" mode.

"Draconian" heap-checking is appropriate for those who like to be very precise about their memory management, and want the heap-checker to help them > enforce it. In "draconian" mode, the heap-checker does not do "live object" checking at all, so it reports a leak unless all allocated memory is freed before > program exit. (However, you can use IgnoreObject() to re-enable liveness-checking on an object-by-object basis.)

"Normal" mode, as the name implies, is the one used most often at Google. It's appropriate for everyday heap-checking use.

2.3 查看报告--text版本

pprof  ./test_tools_forward /tmp/test_tools_forward.19756._main_-end.heap --text

2.4 查看报告--pdf版本

pprof ./test_tools_forward /tmp/test_tools_forward.19756._main_-end.heap --pdf > heap_forward.pdf

3. 同系列文章:

gperftools之cpu-profiler使用小结

posted @ 2022-01-03 15:43  liyakai  阅读(889)  评论(0编辑  收藏  举报