- // Test_Boost_Unordered.cpp : 定義控制臺應(yīng)用程序的入口點。
- //
-
- #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;
- }
執(zhí)行結(jié)果:
50000000
false
second - first 12
third - second 3
50000000
false
second - first 52
third - second 15
運行環(huán)境:
windows -- vs -- Release -- win32
內(nèi)存消耗: boost::unordered_map 消耗 1.2 G, std::map 1.5 G
結(jié)論: unordered_map 查找效率快五倍,插入更快,節(jié)省一定內(nèi)存。如果沒有必要排序的話,盡量使用 hash_map(unordered_map 就是 boost 里面的 hash_map 實現(xiàn))。