我想计算内存分配调用的数量(malloc,calloc,new ...)在我的程序里。该程序积极使用STL容器。主要目的是对所有这些容器中的内存分配进行计数。稍后我将使用这些信息来优化性能。我的程序是在C++上编写的,在Linux下运行。有什么工具可以做到这一点吗?
发布于 2015-02-26 00:16:14
发布于 2019-11-04 21:09:57
您可以重载operator new
#include <stdlib.h>
int numOfHeapAllocations = 0;
void* operator new(size_t size)
{
numOfHeapAllocations++;
return malloc(size);
}只要把它放在你的主文件中的第一件事。
发布于 2015-02-26 03:35:07
下面是我在用于linux的C++开发环境中做的一些工作。您可能需要将iostream更改为stdio.h,将cstdlib更改为stdlib.h (可能还需要更改std以匹配windows名称空间)才能使其在windows中工作。
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <cstdlib>
static char **ms;
using namespace std;
class frag{
public:
int xyz;
};
int numsegments(char** segs){
return strlen((const char*)segs)/sizeof(char*);
}
void randomfunction1(){
ms[numsegments(ms)]=(char*)malloc(100);
}
void randomfunction2(){
ms[numsegments(ms)]=(char*)calloc(1,100);
}
void randomfunction3(){
ms[numsegments(ms)]=(char*)new frag(); //storing class as flat data in memory
int segct=numsegments(ms); // get segments
frag* init=(frag*)ms[--segct]; // subtract 1 from segment count before reading
init->xyz=1; // set variable in class
}
int main(int argc, char *argv[]){
ms=(char**)calloc(1,1000); //store up to 1000 indexes
printf("Segments used so far: %d\n",numsegments(ms));
randomfunction1();
randomfunction2();
randomfunction3();
int total=numsegments(ms);
printf("Segments used total: %d\n",numsegments(ms));
int lastsegment=total-1;
frag* y=(frag*)ms[lastsegment]; //convert to class
printf("xyz in class = %d\n",y->xyz);
for (int i=0;i<total;i++){free(ms[i]);} //free all segments
free(ms);
return 0;
}我理解它的复杂性,但这个程序的基本思想是分配一块内存来存储指向内存片段的指针,然后为每个片段分配任何内存,然后使用strlen()快速计算片段的数量。我知道你把它们算作分配,但我称它们为碎片。
https://stackoverflow.com/questions/28723540
复制相似问题