gperf heap profiler

前言

gperf tools有很多功能,其中有一个heap profiler,可按函数级别定位分配内存的累积量

原理

gperf tools需要替换libc的malloc库,替换为tcmalloc:thread cache malloc,通过在tcmalloc加打桩,即可定位函数级别的内存的累积量

使用方法

工具准备

  1. git clone gperftools;切换至最新的稳定tag;
  2. 编译:autogen.sh && ./configure --prefix=/home/xxx/gperf_release/ && make all && make install
  3. 在gperf_release目录可得到libtcmalloc.a, pprof工具

程序准备

  1. 链接libtcmalloc.a;
  2. 假如监控的是整个程序, 可这样打桩:
    • 引用头文件:gperf_release/include/gperftools/heap-profiler.h
    • 在main函数的起始位置加入:HeapProfilerStart("/tmp/heap_prof"); 其中参数是log存放路径;
    • 在main函数的结束位置加入:HeapProfilerStop();
    • 为了确保程序退出时能执行“HeapProfilerStop”,可在这句代码前面增加while循环,当收到SIGINT时,退出循环,调用此函数;

运行测试

假设可执行程序名为run_test

  1. 程序启动: env HEAP_PROFILE_TIME_INTERVAL="5" run_test
  2. 程序运行后,每隔5秒会产生一个heap文件:/tmp/heap_prof.00xx.heap
  3. 查看heap占用信息:/home/xxx/gperf_release/bin/pprof --text run_test /tmp/heap_prof.00xx.heap
原文地址:https://www.cnblogs.com/zengjianrong/p/11777248.html