【发布时间】:2009-06-29 01:39:13
【问题描述】:
我正在交叉一些数字集,并通过存储每次在地图中看到数字时的计数来做到这一点。
我发现性能非常缓慢。
详情: - 其中一组有 150,000 个数字 - 该组和另一组的交集第一次大约需要300ms,第二次大约需要5000ms - 我还没有进行任何分析,但是每次我在 malloc.c 中进行交集时都会中断调试器!
那么,我怎样才能提高这种性能呢?切换到不同的数据结构?一些如何提高map的内存分配性能?
更新:
- 有什么方法可以询问 std::map 或 boost::unordered_map 预分配 一些空间?
- 或者,有什么技巧可以有效地使用这些技巧吗?
更新2:
见Fast C++ container like the C# HashSet<T> and Dictionary<K,V>?
更新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();
}
【问题讨论】:
-
我建议对其进行分析以收集更多信息。如果您要分配大型数据结构,则 malloc 是一种可能性。
-
如果我在地图中注释掉插入和查找,然后在我的集合中旋转,时间会大大缩短。 90% 的时间都花在了地图上。我尝试切换到 boost::unordered_map,结果相同。
-
嗨,Alex,你的最终版本是什么?还在使用 std::set 吗?还是排序向量? [出于兴趣]谢谢。
标签: c++ stl map intersection