我正在交叉一些数字集,并通过存储每次在地图中看到数字时的计数来做到这一点。
我发现性能非常缓慢。
详细信息:-其中一组包含 150,000 个数字-该组和另一组的交集第一次大约需要 300 毫秒,第二次大约需要 5000 毫秒-我还没有进行任何分析,但每次我打破在 malloc.c 中进行交集时的调试器!
那么,我该如何提高这种性能呢?切换到不同的数据结构?一些如何提高map的内存分配性能?
更新:
- 有没有办法让 std::map 或 boost::unordered_map 预先分配一些空间?
- 或者,是否有任何有效使用这些的技巧?
更新2:
请参阅像 C# HashSet<T> 和 Dictionary<K,V> 这样的快速 C++ 容器?
更新3:
我对 set_intersection 进行了基准测试并得到了可怕的结果:
(set_intersection) Found 313 values in the intersection, in 11345ms
(set_intersection) Found 309 values in the intersection, in 12332ms
代码:
int runIntersectionTestAlgo()
{
set<int> set1;
set<int> set2;
set<int> intersection;
// Create 100,000 values for set1
for ( int i = 0; i < 100000; i++ )
{
int value = 1000000000 + i;
set1.insert(value);
}
// Create 1,000 values for set2
for ( int i = 0; i < 1000; i++ )
{
int random = rand() % 200000 + 1;
random *= 10;
int value = 1000000000 + random;
set2.insert(value);
}
set_intersection(set1.begin(),set1.end(), set2.begin(), set2.end(), inserter(intersection, intersection.end()));
return intersection.size();
}