如何使用TCMalloc?

Cha*_*erV 11 tcmalloc

首先,我想知道如何TCmalloc在Ubuntu中安装.然后我需要一个程序使用TCmalloc.然后我需要一个小程序来表明它TCmalloc比工作更好PTmalloc.

小智 6

安装:

sudo apt-get install google-perftools
Run Code Online (Sandbox Code Playgroud)

在 eclipse 或任何其他代码编写器中创建应用程序

#include <iostream>
#include <unistd.h>
#include <vector>
#include <string>

using namespace std;

class BigNumber
{
public:

BigNumber(int i)
{
  cout << "BigNumber(" << i  << ")" << endl;
  digits = new char[100000];
}

~BigNumber()
{
  if (digits != NULL)
    delete[] digits;
}

private:

char* digits = NULL;

};

int main() {
  cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

  vector<BigNumber*> v;

  for(int i=0; i< 100; i++)
  {
    v.push_back(new BigNumber(i));
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码将帮助您了解内存泄漏情况

然后将库添加到您的 makefile

-ltcmalloc
Run Code Online (Sandbox Code Playgroud)

运行应用程序时,要创建堆文件,因此需要添加环境变量 HEAPPROFILE=/home/myuser/prefix 并且文件 prefix.0001.heap 将创建在 /home/myuser 路径中

运行应用程序,将创建堆文件 检查堆文件

pprof helloworld helloworld.0001.heap --text
Using local file helloworld.
Using local file helloworld.0001.heap.
Total: 9.5 MB
  9.5 100.0% 100.0%      9.5 100.0% BigNumber::BigNumber
  0.0   0.0% 100.0%      0.0   0.0% __GI__IO_file_doallocate
Run Code Online (Sandbox Code Playgroud)

很容易看到哪些对象泄漏了,它们被分配到了哪里。


juh*_*ist 5

我将提供另一个答案,因为比其他答案更容易安装:

Ubuntu已经有一个用于Google perf工具的软件包:http ://packages.ubuntu.com/search?keywords=google-perftools

通过安装libgoogle-perftools-dev,您应该获得开发tcmalloc应用程序所需要的全部。至于如何实际使用tcmalloc,请参见其他答案。


Ori*_*ent 5

安装TCMalloc

sudo apt-get install google-perftools
Run Code Online (Sandbox Code Playgroud)

要以系统范围的方式替换分配器,我编辑/etc/environment(或从/etc/profile,导出/etc/profile.d/*.sh):

echo "LD_PRELOAD=/usr/lib/libtcmalloc.so.4" | tee -a /etc/environment
Run Code Online (Sandbox Code Playgroud)

做同样在更窄的范围,您可以编辑~/.profile~/.bashrc/etc/bashrc,等。


大宝剑*_*大宝剑 1

  1. tcmallocgoogle perf 工具中,安装指南可以在这里找到。
  2. 该示例包含在google perf 工具中
  3. 请参阅此处的性能说明部分