繁体   English   中英

如何减少unordered_multiset的内存消耗?

[英]How to reduce the memory consumption of unordered_multiset?

由于以下两个原因,我在代码中使用了unordered_multiset:

  1. 应该容易找到或查找数据。
  2. 应该支持加载重复值。

无论是插入还是查找,有时甚至是删除,unordered_multiset通常都比multisets和vector快得多。

但是不好的是,它占用了太多的内存。

我已将unsigned __int64(8字节)值存储在unordered_multiset中,并从unordered_multiset中正确清除了这些值。 谁能解释一下,为什么要占用内存以及如何解决此内存消耗?

通过为std::容器提供一个自定义的分配器来记录它需要分配的空间,您可以更好地衡量std::容器使用的空间。

例如

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;
}

Caleth有一个很好的建议,或者您可以查看进程中的内存使用情况

在您插入多重集之前和之后。

最可能的区别是,加载了巨大的dll。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM