分享

boost::unordered_map 和 std::map 的效率,内存比较

 wtkc 2014-10-25

分类: C++ 标准 2012-06-28 11:13 4090人阅读 评论(0) 收藏 举报

  1. // Test_Boost_Unordered.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "boost/unordered_map.hpp"  
  6. #include <iostream>  
  7. #include <map>  
  8. #include "time.h"  
  9.   
  10. using namespace std;  
  11. int _tmain(int argc, _TCHAR* argv[])  
  12. {  
  13.     {  
  14.     time_t first_time = time(0);  
  15.     boost::unordered_map<int, int> test_hash;  
  16.     for (int i = 0; i < 50000000; i++)  
  17.     {  
  18.         test_hash.insert(std::pair<int, int>(i, i));  
  19.     }  
  20.     cout << test_hash.size() << endl;  
  21.       
  22.     time_t second_time = time(0);  
  23.   
  24.     for (int i = 0; i< 50000001; ++i)  
  25.     {  
  26.         boost::unordered_map<int, int>::iterator iter = test_hash.find(i);  
  27.         if (iter == test_hash.end())  
  28.         {  
  29.             cout << "false" << endl;  
  30.         }  
  31.     }  
  32.     time_t third_time = time(0);  
  33.     cout << "second - first " << second_time - first_time << endl;  
  34.     cout << "third - second " << third_time - second_time << endl;  
  35.     }  
  36.   
  37.     {  
  38.     time_t first_time = time(0);  
  39.     std::map<int, int> test_hash;  
  40.     for (int i = 0; i < 50000000; i++)  
  41.     {  
  42.         test_hash.insert(std::pair<int, int>(i, i));  
  43.     }  
  44.     cout << test_hash.size() << endl;  
  45.   
  46.     time_t second_time = time(0);  
  47.   
  48.     for (int i = 0; i< 50000001; ++i)  
  49.     {  
  50.         std::map<int, int>::iterator iter = test_hash.find(i);  
  51.         if (iter == test_hash.end())  
  52.         {  
  53.             cout << "false" << endl;  
  54.         }  
  55.     }  
  56.     time_t third_time = time(0);  
  57.     cout << "second - first " << second_time - first_time << endl;  
  58.     cout << "third - second " << third_time - second_time << endl;  
  59.     }  
  60.     return 0;  
  61. }  

执行结果:

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 实现)。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多