为什么Parallel类的For方法会随着时间的推移变得更快?

问题描述

我正在做一些测试,以找出生成的UUID编号中的某些重复项,并且我使用不同的方法来执行计算。它们是multithreadingnormal for loopfor method of the Parallel classMultithreading是明显的赢家,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;
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...