首先,我想知道如何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)
很容易看到哪些对象泄漏了,它们被分配到了哪里。
安装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
,等。
归档时间: |
|
查看次数: |
17814 次 |
最近记录: |