如何测量std :: unordered_map的内存使用情况 [英] How to measure Memory Usage of std::unordered_map
问题描述
我们知道基于哈希表的容器实现,例如 std :: unordered_map
使用大量内存,但是我不知道多少?
We know that hash table based container implementations like std::unordered_map
use a lot memory but I don't know how much is how much?
除了空间复杂度符号外,不考虑容器元素是否是指向更大对象的指针:
Apart from space complexity notations, and not considering if a container element is a pointer to a larger object:
有什么方法可以计算出运行时此类容器使用了多少个字节?
Is there any way to figure out how many bytes is being used by such a container during run-time?
是否有一种方法可以在运行时告诉任何容器使用多少内存?
Is there a way to tell, at runtime, how much memory any container uses?
推荐答案
如果您想获得大致尺寸,我认为 bucket_count()
和 max_load_factor()
是足够,它给出了当前的铲斗数量和负载系数.
If you want to get a rough size, I think bucket_count()
and max_load_factor()
is enough, which gives the current count of buckets and the load factor.
理性:
-
如果
load_factor
< == 1,则表示bucket_count()
> =映射中的项目,则bucket_count()是内存大小用法.
If
load_factor
<= 1, it indicates thatbucket_count()
>= the items in the map, then bucket_count() is the size of memory usage.
如果 load_factor
> 1,则 bucket_count()
* load_factor
表示地图中的最大商品.请注意,这是最大大小,而不是实际大小.
If load_factor
> 1, then bucket_count()
* load_factor
indicates the max item in the map. Note this is the max size, not the real size.
因此,粗略的内存使用情况可能看起来像这样:
So for a rough memory usage could look like this:
unsigned n = mymap.bucket_count();
float m = mymap.max_load_factor();
if (m > 1.0) {
return n * m;
}
else {
return n;
}
如果要获取准确的内存使用情况,则可能需要计算所有存储桶以查看其中的元素数量:
If you want to get the accurate memory usage, you may need to count all the buckets to see how many elements in it:
size_t count = 0;
for (unsigned i = 0; i < mymap.bucket_count(); ++i) {
size_t bucket_size = mymap.bucket_size(i);
if (bucket_size == 0) {
count++;
}
else {
count += bucket_size;
}
}
这篇关于如何测量std :: unordered_map的内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!