STL 容器的内存消耗
我正在开发一个计划在其中使用几个 STL 容器的应用程序.如果内存消耗达到阈值,应用程序将采取某些步骤.为此,我需要对 STL 容器使用的内存量进行接近准确的计算.
I am working on an application in which I am planning to use couple of STL containers. The application will take certain steps if memory consumption reaches a threshold. For that purpose I need to perform a close to accurate calculation on how much memory is used by STL containers.
vector<string> StringList
map<string, int> mapstring
这就是我估计内存的方式:
This is how I am estimating memory:
对于StringList
的大小,循环遍历向量的所有元素并继续添加字符串大小.
For size of StringList
, loop over all the elements of the vector and keep adding the string sizes.
string size = sizeof(string) + string.capacity()*sizeof(char)
然后最后添加到这个sizeof(StringList);
对于 mapstring 的大小,遍历容器的所有键并继续添加字符串大小,然后添加 int 的大小,即 mapstring.size()*sizeof(int)
.然后最后添加到这个 sizeof(mapstring);
For size of mapstring, loop over all the keys of the container and keep adding the string sizes and then add the sizes of int which is mapstring.size()*sizeof(int)
. Then finally add to this sizeof(mapstring);
我想更好的方法是指定自己的分配器类并跟踪其中的内存使用情况,但编写一个可能并非易事.这个估计好看吗?
I guess a better approach would be specifying own allocator class and keeping track of memory usage inside it but writing one could be non-trivial. Does this estimation look good ?
推荐答案
对于 std::vector
和 std::string
,容量而不是大小是一个更好的近似.对于基于节点的容器 (std::set
,等),你想要乘以节点的数量(大约是元素)乘以每个节点的大小.然而,这仅是准确的,如果分配器不为节点使用优化的池分配器.
For std::vector
and std::string
, capacity, rather than size, would
be a better approximation. For node based containers (std::set
,
etc.), you'd want multiply the number of nodes (roughly the number of
elements) times the size of each node. This only accurate, however, if
the allocator doesn't use an optimized pool allocator for the nodes.
如果你真的想知道有多少内存被使用,但是,更好的策略是替换全局 operator new
和operator delete
,并跟踪实际分配.更准确的是替换 malloc
和 free
.正式地,这不是允许,但在实践中,我从未遇到过这样的实现它不起作用.另一方面,如果你替换 malloc
和 free
,您必须自己实现实际的内存管理.如果你替换operator new
和operator delete
,你可以使用malloc
和免费
,这使它变得相当简单.
If you really want to know how much memory is being used, however, a
better strategy would be to replace the global operator new
and
operator delete
, and keep track of the actual allocations. Even more
accurate would be to replace malloc
and free
. Formally, this is not
allowed, but in practice, I've never encountered an implementation where
it doesn't work. On the other hand, if you replace malloc
and free
,
you have to implement the actual memory management yourself. If you
replace operator new
and operator delete
, you can use malloc
and
free
, which makes it fairly trivial.
还要注意,每个分配都有一些固定的开销.一个 100000每个 10 字节的分配将比10 次分配,每次 100000 字节.
Note too that each allocation has some fixed overhead. A 100000 allocations of 10 bytes each will consume significantly more memory than 10 allocations of 100000 bytes each.
相关文章