优化boost无序映射和集合,C ++

时间:2009-05-19 03:47:46

标签: c++ c++11

我将解析60GB的文本并在地图中进行大量的插入和查找。 我刚开始使用boost :: unordered_set和boost :: unordered_map 随着我的程序开始填充这些容器,他们开始变得越来越大,我想知道为这些容器预先分配内存是否是一个好主意。 就像是     mymap中:: get_allocator()分配(N)。 ?

或者我应该让他们自己分配并找出成长因素? 代码看起来像这样

boost::unordered_map <string,long> words_vs_frequency, wordpair_vs_frequency;   
boost::unordered_map <string,float> word_vs_probability, wordpair_vs_probability,
           wordpair_vs_MI;                  
//... ... ...                                   

N = words_vs_frequency.size();
long   y =0; float MIWij =0.0f, maxMI=-999999.0f;
for (boost::unordered_map <string,long>::iterator i=wordpair_vs_frequency.begin(); 
                     i!=wordpair_vs_frequency.end(); ++i){
if (i->second >= BIGRAM_OCCURANCE_THRESHOLD)
    {
    y++;
    Wij = i->first;
    WordPairToWords(Wij, Wi,Wj);
    MIWij =  log ( wordpair_vs_probability[Wij] /
             (word_vs_probability[Wi] * word_vs_probability[Wj]) 
            );

    // keeping only the pairs which MI value greater than 
    if (MIWij > MUTUAL_INFORMATION_THRESHOLD)
        wordpair_vs_MI[ Wij ] = MIWij;
    if(MIWij > maxMI )
        maxMI = MIWij; 
    }

   }

提前致谢

3 个答案:

答案 0 :(得分:11)

根据the documentationunordered_setunordered_map都有方法

void rehash(size_type n);

重新生成哈希表,使其至少包含n个桶。 (听起来它像reserve()对STL容器所做的那样。)

答案 1 :(得分:4)

我会尝试两种方式,这将让您生成硬数据,显示一种方法是否比另一种更好。我们可以整天推测哪种方法是最优的,但与大多数性能问题一样,最好的办法是尝试一下,看看会发生什么(然后修复实际需要修复的部分)。

话虽如此,Boost的作者似乎非常聪明,所以它很可能会正常工作。你只需要测试一下。

答案 2 :(得分:0)

老实说,我认为你最好自己编写自己的分配器。例如,您可以使用名为preallocate(int N)的方法创建一个分配器,该方法将保留N个字节,然后使用unordered_map::get_allocator()来获得所有乐趣。此外,使用您自己的分配器,您可以告诉它一次抓取大块。