ubuntu18使用google-perftools并生成火焰图

欧阳德运
2023-12-01

一,安装google-perftools:

sudo apt-get install google-perftools libgoogle-perftools-dev

二,测试代码:

注意要在代码中加入tcmalloc和profiler。

CMakeLists.txt和main.cpp文件:

CMAKE_MINIMUM_REQUIRED (VERSION 3.5)
set(PROJECT_NAME "Testgoogleperftools")
project("${PROJECT_NAME}")

file(GLOB_RECURSE PROJECT_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")

add_executable(${PROJECT_NAME} "${PROJECT_SRC}")

target_link_libraries(${PROJECT_NAME}
   tcmalloc
   profiler
)
#include <iostream>

int main(int argc, char *argv[])
{
   std::cout << "test start" << std::endl;

   while (true)
   {
      int * p = new int;
      delete p;
   }
   
   std::cout << "test end" << std::endl;
   return 1;
}

三,性能分析:

性能分析不要求程序是否能够正常退出,可以在程序运行的任意时间开始和结束检测。

1,执行程序:

LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libprofiler.so CPUPROFILE=cpu.prof CPUPROFILESIGNAL=12 ./Testgoogleperftools

2,开始收集信息:

killall -12 Testgoogleperftools

3,结束收集信息:

killall -12 Testgoogleperftools

4,分析性能,生成火焰图:

google-pprof --collapsed ./Testgoogleperftools cpu.prof.0 > cpu.prof
# 需要下载flamegraph
/home/$USER/FlameGraph/flamegraph.pl cpu.prof > cpu.svg

四,内存泄露分析:

内存泄漏的检测要求程序能够正常退出,并在程序退出时生成检测结果。

1,修改代码如下:

#include <iostream>

int main(int argc, char *argv[])
{
   std::cout << "test start" << std::endl;

   int * p = new int;
   p = new int;
   delete p;

   std::cout << "test end" << std::endl;
   return 1;
}

2,执行程序:

LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc.so HEAPCHECK=normal HEAP_CHECK_DUMP_DIRECTORY=./ PPROF_PATH=/usr/bin/google-pprof ./Testgoogleperftools

3,生成内存泄漏火焰图:

google-pprof --collapsed ./Testgoogleperftools Testgoogleperftools.32058._main_-end.heap > leak.prof
# 需要下载flamegraph
/home/$USER/FlameGraph/flamegraph.pl leak.prof > leak.svg

 类似资料: