我正在做一些测试以找出生成的 UUID 数字中的一些重复项,并且我使用不同的方法来执行计算。这些是multithreading, anormal for loop和for method of the Parallel class. Multithreading是明显的赢家,随着时间的推移,方法变得越来越normal for loop松散。Parallel.For我已经用 10 次测试,Parallel.For它从 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;
}