【发布时间】:2009-06-29 16:54:17
【问题描述】:
我在 STL 中使用 set_intersection 将一组 100,000 个数字和一组 1,000 个数字相交,它需要 21 秒,而在 C# 中需要 11 毫秒。
C++ 代码:
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();
}
C#代码:
static int runIntersectionTest()
{
Random random = new Random(DateTime.Now.Millisecond);
Dictionary<int,int> theMap = new Dictionary<int,int>();
List<int> set1 = new List<int>();
List<int> set2 = new List<int>();
// Create 100,000 values for set1
for ( int i = 0; i < 100000; i++ )
{
int value = 1000000000 + i;
set1.Add(value);
}
// Create 1,000 values for set2
for ( int i = 0; i < 1000; i++ )
{
int value = 1000000000 + (random.Next() % 200000 + 1);
set2.Add(value);
}
// Now intersect the two sets by populating the map
foreach( int value in set1 )
{
theMap[value] = 1;
}
int intersectionSize = 0;
foreach ( int value in set2 )
{
int count;
if ( theMap.TryGetValue(value, out count ) )
{
intersectionSize++;
theMap[value] = 2;
}
}
return intersectionSize;
}
}
【问题讨论】:
-
这不是一个有用的评论:你是在计时整个程序,还是只是 set_intersection() 调用?
-
您是否正在计时初始集合的创建以及交叉点的创建时间?
-
您确实意识到 C++ std::set 是一个基于树的结构,而 C# Dictionary 是一个基于数组的哈希表,而 List 只是一个数组,对吧?在考虑代码的分配问题之前,您已经在比较苹果和橙子了。
-
除了以上问题。在 C# 示例中,您没有构建集合的交集(只是获取大小)。您需要进行第三次传递并从“theMap”中删除仅在 set1 中的所有成员。
-
你如何编译这个?其他人似乎无法重现您的时间安排。
标签: c# c++ performance stl intersection