我正在做一些测试,以找出生成的UUID编号中的某些重复项,并且我使用不同的方法来执行计算。它们是multithreading
,normal for loop
和for method of the Parallel class
。 Multithreading
是明显的赢家,normal for loop
则更宽松,Parallel.For
方法随着时间的推移变得越来越快。我用Parallel.For
做了10次测试,它从18.08秒减少到11.80秒。我一直在启动项目,一次执行一个测试,所以我相信它不能存储在内存中。在测试期间,我没有在计算机上做任何其他事情。
这些是Parallel.For
方法的测试结果:
1: 00:00:18.08
2: 00:00:17.04
3: 00:00:16.79
4: 00:00:15.15
5: 00:00:13.00
6: 00:00:12.69
7: 00:00:12.66
8: 00:00:12.54
9: 00:00:12.33
10: 00:00:11.80
对此有逻辑解释吗?
如果需要的话,这里是代码:
// In Main
Parallel.For(0, 10, i =>
{
TestForUUIDDuplicates(i + 1);
});
static void TestForUUIDDuplicates(object loopIndex)
{
if (!(loopIndex is int))
{
throw new InvalidCastException();
}
var uuids = new List<string>();
for (int i = 0; i < 1000000; i++)
{
if (i % 100000 == 0) System.Console.WriteLine("Reached {0} in loop {1}", i, loopIndex);
uuids.Add(GenerateUUID());
}
System.Console.WriteLine("Finished adding UUIDs in loop {0}.", loopIndex);
var duplicates = uuids
.GroupBy(uuid => uuid)
.SelectMany(group => group.Skip(1)).ToList();
System.Console.WriteLine("Finished finding duplicates in loop {0}.", loopIndex);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}
if (duplicates.Count == 0)
{
Console.WriteLine("No duplicates found in loop {0}.", loopIndex);
}
else
{
_duplicates.AddRange(duplicates);
}
Console.WriteLine("Finished loop {0}", loopIndex);
}
private static string GenerateUUID()
{
// var ticks = DateTime.Now.Ticks;
var ticks = DateTime.Now.Ticks;
var guid = Guid.NewGuid().ToString();
return ticks.ToString() + '-' + guid;
}