【问题标题】:How to count number of memory allocations如何计算内存分配的数量
【发布时间】:2015-04-27 17:07:42
【问题描述】:

我想在我的程序中计算内存分配调用(malloc、calloc、new ...)的数量。该程序积极使用 STL 容器。 主要目的是计算所有这些容器内的内存分配。稍后我将使用这些信息来优化性能。 我的程序是用 C++ 编写的,在 Linux 下运行。有什么工具可以做到吗?

【问题讨论】:

  • 你看过 valgrind 吗?
  • 如果您只想计算分配的字节总数,可以使用 valgrind。如果您想计算malloc 调用的数量,那么最简单的方法是为其编写一个包装器 - 请参阅this question
  • This page 有一个有用的示例(特定于glibc),每次调用malloc 时都会打印出信息。您可以使用类似的代码来增加一个全局计数器。
  • 你有什么内核版本/glibc 版本/发行版?我建议您尝试SystemTap,但它需要 glibc debuginfo 和内核 3.5+(最低版本的 rhel 内核可能有特殊补丁)。
  • 我查看了 valgrind。它似乎只显示分配的字节总数。但也许有一些特定的工具可以显示位置的数量。

标签: c++ linux memory-management


【解决方案1】:

您可以重新定义要计算的运算符。

示例:How to use operator new to count number of times of dynamic memory allocation

【讨论】:

  • 我认为只是重载运算符“new”对我没有帮助(我认为标准 stl 分配器通常使用 malloc 分配内存,而不是使用placement new 将对象放在那里。但也有一个指向内存分配的链接钩子,也许我可以尝试使用它们。
【解决方案2】:

你可以重载operator new:

#include <stdlib.h>

int numOfHeapAllocations = 0;

void* operator new(size_t size)
{
    numOfHeapAllocations++;
    return malloc(size);
}

把它放在你的主文件的第一件事。

【讨论】:

    【解决方案3】:

    这是我在我的 C++ 开发环境中为 linux 准备的东西。 您可能需要将 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() 快速计算片段。我知道您将它们视为分配,但我称它们为片段。

    【讨论】:

    • 对不起,我不明白你的想法。主要问题是计算在 stl 容器(向量、字符串等)内完成了多少重新定位。您的解决方案如何帮助做到这一点?
    猜你喜欢
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 2012-11-25
    • 2013-11-05
    • 2020-06-08
    • 2016-04-29
    相关资源
    最近更新 更多