c++ - 如何通过boost bimap查找内存占用

标签 c++ memory boost-bimap

我有一个boost bimap

#include <iostream>
#include <utility>
#include <boost/bimap.hpp>
#include <boost/bimap/set_of.hpp>
#include <boost/bimap/multiset_of.hpp>

namespace bimaps = boost::bimaps;
typedef boost::bimap<bimaps::set_of<unsigned long long int>,
        bimaps::multiset_of<unsigned long long int > > bimap_reference;
typedef bimap_reference::value_type position;
bimap_reference numbers;

int main()
{
    numbers.insert(position(12345689, 1000000000));
    numbers.insert(position(23456789, 8000000000));   
    return 0;
}

我有大约 180000000 个条目。理论上它应该占用 ~2.7GB 的空间(180000000*8*2 = 2880000000 字节 = 2880000000/1024*1024*1024 = ~2.7GB )。现在我想找到 boost bimap 占用的实际空间,我该怎么做。

最佳答案

就像您提到的问题下的评论一样,您可以重载 newdelete 运算符来跟踪内存分配和释放。 this全局替换 部分下的示例文章展示了一个非常简单的例子:

void* operator new(std::size_t sz) {
    std::printf("global op new called, size = %zu\n", sz);
    return std::malloc(sz);
}
void operator delete(void* ptr) noexcept {
    std::puts("global op delete called");
    std::free(ptr);
}

此示例的唯一问题是您无法确定释放了多少内存。要解决此问题,请查看 accepted answerHow to track memory allocations in C++ (especially new/delete)问题。

上述答案中的示例使用带有自定义分配器的 std::map 来存储已分配内存块的地址和大小。在 delete 运算符重载中,它删除具有指定地址的元素。几乎无需修改即可满足您的要求:

#include <map>

template<typename T>
struct MemoryMapAllocator : std::allocator<T> {
    typedef typename std::allocator<T>::pointer pointer;
    typedef typename std::allocator<T>::size_type size_type;
    template<typename U> struct rebind { typedef MemoryMapAllocator<U> other; };

    MemoryMapAllocator() {}

    template<typename U>
    MemoryMapAllocator(const MemoryMapAllocator<U>& u) : std::allocator<T>(u) {}

    pointer allocate(size_type size, std::allocator<void>::const_pointer = 0) {
        void* p = std::malloc(size * sizeof(T));
        if(p == 0)
            throw std::bad_alloc();
        return static_cast<pointer>(p);
    }
    void deallocate(pointer p, size_type) {
        std::free(p);
    }
};

typedef std::map<void*, std::size_t, std::less<void*>,
            MemoryMapAllocator<std::pair<void* const, std::size_t>>> MemoryMap;

MemoryMap& getMemoryMap() {
    static MemoryMap memMap;
    return memMap;
}

std::size_t totalAllocatedMemory() {
    std::size_t sum = 0;
    for(auto& e : getMemoryMap())
        sum += e.second;
    return sum;
}

void* operator new(std::size_t size) {
    void* mem = std::malloc(size == 0 ? 1 : size);

    if(mem == 0)
        throw std::bad_alloc();

    getMemoryMap()[mem] = size;
    return mem;
}

void operator delete(void* mem) {
    getMemoryMap().erase(mem);
    std::free(mem);
}

Live Demo

关于c++ - 如何通过boost bimap查找内存占用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45114932/

相关文章:

PHP exec() 使用内存

ios - MapBox 导致由于内存问题而终止

c++ - 声明 C++ 中的冲突说明符

c++ - 使用 bimap 中的键访问值

c++ - 定义一个成员类后重新声明它合法吗?

C++通过命令行应用程序将要列表的字符串添加到txt文件

C++ Typedef 和运算符重载

c++ - 没有重载函数 "search"的实例与参数列表匹配

c++ - 递归函数删除链表中字符的所有实例

ajax - uiComponent树内存使用情况