我有两个无序映射:(代码在linux中执行)
第一个无序 map :
它包含至少 65536 个条目。每个条目包含
int
unsigned char
unsigned char
第二个无序 map :
它包含少于 65536 个条目。每个条目包含
int
int
int
vector <char>
现在我想根据上面两个无序映射占用的内存(以字节为单位)对两者进行比较。之后我想计算实现的内存压缩。 请指导我如何找到两个无序映射占用的内存?
第二个无序 map 的更多详细信息:
typedef std::tuple<int, int> key_t;
struct KeyHasher
{
std::size_t operator()(const key_t& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(std::get<0>(k)));
hash_combine(seed,hash_value(std::get<1>(k)));
// Return the result.
return seed;
}
};
struct Ndata
{
int value;
vector<char> accept ;
};
typedef boost::unordered_map<const key_t,Ndata,KeyHasher> SecondMap;
}
最佳答案
我认为,如果不查看您的 STL 使用的精确 unordered_map
实现,就不可能准确回答您的问题。
但是,基于 unordered_map
interface ,你可以做出合理的猜测:
unordered_map
需要存储:
一个
bucket
容器(可能是一个类似 vector 的结构)max_bucket_count
个存储桶(可能是类似单链表的结构)每个项目都有一个完整的条目(不仅是值,还有键,以处理键哈希冲突)
快速浏览一下 Libc++ 实现后,您还需要空间来存储:
哈希函数对象
相等性测试函数对象
分配器函数对象
考虑到这一点,我的猜测是这样的:
typedef unordered_map<K, V, ...> tMyMap;
size_t getMemoryUsage(const tMyMap& map) {
auto entrySize = sizeof(K) + sizeof(V) + sizeof(void*);
auto bucketSize = sizeof(void*);
auto adminSize = 3 * sizeof(void*) + sizeof(size_t);
auto totalSize = adminSize + map.size() * entrySize + map.max_bucket_count() * bucketSize();
return totalSize;
}
这仅适用于第一种情况,因为在第二种情况下,根据每个 vector 的大小,每个条目可以具有完全不同的内存使用量。对于第二种情况,您必须添加如下内容:
size_t getMemoryUsage(const tMyMap& map) {
auto entrySize = sizeof(K) + sizeof(V) + sizeof(void*);
auto bucketSize = sizeof(void*);
auto adminSize = 3 * sizeof(void*) + sizeof(size_t);
auto totalSize = adminSize + map.size() * entrySize + map.max_bucket_count() * bucketSize();
auto contentSize = 0;
for (const auto& kv : map) {
// since accept is a vector<char>,
// it uses capacity() bytes of additional memory
contentSize += kv.second.accept.capacity();
}
totalSize += contentSize;
return totalSize;
}
但是,考虑到现实世界的分配逻辑,您的 map 实际使用的内存可能与此有很大不同,例如由于外部碎片。如果您想 100% 确定 unordered_map 使用了多少内存,则还需要考虑分配器行为。
关于c++ - 计算无序映射占用的内存空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22498768/