Posted on 2012-07-26 10:44
点点滴滴 阅读(2015)
评论(0) 编辑 收藏 引用 所属分类:
02 编程语言
#include "stdafx.h"
#include "boost/unordered_map.hpp"
#include <iostream>
#include <map>
#include "time.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
{
time_t first_time = time(0);
boost::unordered_map<int, int> test_hash;
for (int i = 0; i < 50000000; i++)
{
test_hash.insert(std::pair<int, int>(i, i));
}
cout << test_hash.size() << endl;
time_t second_time = time(0);
for (int i = 0; i< 50000001; ++i)
{
boost::unordered_map<int, int>::iterator iter = test_hash.find(i);
if (iter == test_hash.end())
{
cout << "false" << endl;
}
}
time_t third_time = time(0);
cout << "second - first " << second_time - first_time << endl;
cout << "third - second " << third_time - second_time << endl;
}
{
time_t first_time = time(0);
std::map<int, int> test_hash;
for (int i = 0; i < 50000000; i++)
{
test_hash.insert(std::pair<int, int>(i, i));
}
cout << test_hash.size() << endl;
time_t second_time = time(0);
for (int i = 0; i< 50000001; ++i)
{
std::map<int, int>::iterator iter = test_hash.find(i);
if (iter == test_hash.end())
{
cout << "false" << endl;
}
}
time_t third_time = time(0);
cout << "second - first " << second_time - first_time << endl;
cout << "third - second " << third_time - second_time << endl;
}
return 0;
}
执行结果:
50000000
false
second - first 12
third - second 3
50000000
false
second - first 52
third - second 15
运行环境:
windows -- vs -- Release -- win32
内存消耗: boost::unordered_map 消耗 1.2 G, std::map 1.5 G
结论: unordered_map 查找效率快五倍,插入更快,节省一定内存。如果没有必要排序的话,尽量使用 hash_map(unordered_map 就是 boost 里面的 hash_map 实现)。