2017-08-04 111 views
0

我用unordered_multiset在我的代碼由以下兩個原因,如何減少unordered_multiset的內存消耗?

  1. 應該很容易找到或查找數據。
  2. 應該支持加載重複值。

unordered_multiset通常比多集&向量,都用於插入和用於查找要快得多,有時甚至爲刪除。

但不好的是,它需要太多的內存。

我在unordered_multiset中存儲了未簽名的__int64(8字節)值並正確清除了unordered_multiset中的值。 你能解釋一下嗎,爲什麼它取內存&如何解決這個內存消耗問題?

+4

你是如何測量內存消耗的? – Drek

+0

@Drek我從任務管理器中獲得了內存消耗細節。我發現它使用我的應用程序的進程ID。 – Durai

+2

你插入了多少個* distinct *項目?一旦所有值都被插入,'unordered_multiset'的內存佔用量有多大? – dasblinkenlight

回答

0

通過向容器提供一個自定義分配器來記錄需要分配多少空間,您可以更好地衡量容器使用多少空間。

例如

std::size_t total_allocation = 0; 

template< class T > 
struct logging_allocator 
{ 
    using value_type = T; 
    using pointer = T*; 
    using const_pointer = const T*; 
    using reference = T&; 
    using const_reference = const T&; 
    using size_type = std::size_t; 
    using difference_type = std::ptrdiff_t; 
    using propagate_on_container_move_assignment = std::true_type; 
    template< class U > struct rebind { using other = logging_allocator<U>; }; 
    using is_always_equal = std::true_type; 

    pointer address(reference x) const { return base.address(x); } 
    const_pointer address(const_reference x) const{ return base.address(x); } 

    pointer allocate(size_type n, const_pointer hint = nullptr){ 
     total_allocation += n; 
     return base.allocate(n, hint); 
    } 
    pointer allocate(size_type n, const void * hint){ 
     total_allocation += n; 
     return base.allocate(n, hint); 
    } 
    pointer allocate(size_type n){ 
     total_allocation += n; 
     return base.allocate(n, hint); 
    } 

    void deallocate(T* p, size_type n) { 
     total_allocation -= n; 
     return base.deallocate(p, n); 
    } 

    size_type max_size() const { 
     return base.max_size(); 
    } 

    void construct(pointer p, const_reference val) { 
     total_allocation += sizeof(T); 
     return base.construct(p, val); 
    } 
    template< class U, class... Args > 
    void construct(U* p, Args&&... args) { 
     total_allocation += sizeof(U); 
     return base.construct(p, args...); 
    } 

    void destroy(pointer p) { 
     total_allocation -= sizeof(T); 
     return base.destroy(p); 
    } 
    template< class U > 
    void destroy(U* p) { 
     total_allocation -= sizeof(U); 
     return base.destroy(p); 
    } 

private: 
    std::allocator<T> base; 
} 
0

Caleth有好的建議,或者你可以看看memory usage within processes

你插入多集之後之前。

最有可能的過程中,一個巨大的dll被加載。