【发布时间】:2012-08-25 10:49:17
【问题描述】:
我用这段代码测试了它们(在 Visual Studio 2010 sp1 上):
#include <ctime>
#include <iostream>
#include <map>
#include <unordered_map>
#include <hash_map>
int main()
{
clock_t time;
int LOOP = (1 << 16);
std::map<int, int> my_map;
std::unordered_map<int, int> map_unordered_map;
std::hash_map<int, int> my_hash_map;
time = clock();
for (int i = 0; i != LOOP; ++i)
{
my_map[i] = i;
}
std::cout << "map: " << ((double)(clock() - time) / CLOCKS_PER_SEC) << std::endl;
time = clock();
for (int i = 0; i != LOOP; ++i)
{
map_unordered_map[i] = i;
}
std::cout << "unordered_map: " << ((double)(clock() - time) / CLOCKS_PER_SEC) << std::endl;
time = clock();
for (int i = 0; i != LOOP; ++i)
{
my_hash_map[i] = i;
}
std::cout << "hash_map: " << ((double)(clock() - time) / CLOCKS_PER_SEC) << std::endl;
system("PAUSE");
return EXIT_SUCCESS;
}
结果太奇怪了:
在调试中: 地图:0.289 无序地图:10.738 哈希映射:10.58 按任意键继续 。 . .
在发布中: 地图:0.101 无序地图:0.463 哈希映射:0.429 按任意键继续 。 . .
【问题讨论】:
-
可能是
std::map实现特别针对增加密钥插入进行了调整,您应该使用随机数进行测试。也可能是 2^16 太小而无法显示散列容器的理论优势。 -
std::map 使用红黑树作为其内部数据结构,而 std::hash_map 使用哈希表。您所看到的可能是随着哈希表的增长而重新设置哈希表的成本。如果您清除它们并再次运行相同的插入会发生什么?
-
因为如果我将 LOOP 设置得更大,它会变得非常慢,所以最后我将它设置为 1
-
Jens Agby 是对的.....如果我在插入所有元素后第二次循环它,hash_map 比 map 快得多.....
-
添加了一个描述我们发现的答案
标签: c++ map hashmap unordered-map