使用 gperftools 分析程序cpu性能

2023-11-19

一、gperftools 简介

gperftools 是 google 开源的一组套件,提供了高性能的、支持多线程的 malloc 实现,以及一组优秀的性能分析工具。

二、安装 gperftools

2.1、下载源码

从 gperftools github 官网上下载最新版本的源码包:

wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.10/gperftools-2.10.tar.gz

2.2、解压源码包

tar -zxv -f gperftools-2.10.tar.gz

2.3、configure

cd gperftools-2.10
./configure

命令结束执行后出现一个报错:

configure: WARNING: No frame pointers and no libunwind. Using experimental backtrace capturing via libgcc. Expect crashy cpu profiler.

这是因为没有安装 libunwind。这里直接使用 yum 的方式安装:

yum install libunwind-devel

再次执行 ./configure,命令执行成功。

2.4、编译并安装

执行如下两个命令,进行编译并安装:

make
sudo make install

最后执行 ldconfig 更新动态库文件

2.5、确认安装成功

执行如下命令,确认 gperftools 安装成功

[root@36eab gperftools-2.10]# pprof --version
pprof (part of gperftools 2.0)

Copyright 1998-2007 Google Inc.

This is BSD licensed software; see the source for copying conditions
and license information.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
123456789

三、示例

3.1 demo

#include <iostream>
#include <map>
#include <vector>
using namespace std;

void VectorPush() {
  std::vector<int> v;
  for (int i = 0; i < 1000000; ++i) {
    v.push_back(i);
  }
}

void MapPush() {
  std::map<int, int> m;
  for (int i = 0; i < 1000000; ++i) {
    m[i] = i;
  }
}

int main(void) {
  VectorPush();
  MapPush();
}

3.2 编译,并链接profiler库

g++ -std=c++11 main.cpp -o main -lprofiler

3.3 运行

env CPUPROFILE=./profile.prof ./main

profile.prof为生成的文件名

3.4 生成svg格式

pprof ./main ./profile.prof --svg > svg.svg

./main为上面的可执行程序

在浏览器中打开svg.svg文件即可

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 gperftools 分析程序cpu性能 的相关文章