并行For循环与c#中的简单for循环。速度测试

时间:2016-12-26 23:26:51

标签: c# multithreading parallel.for

我对是否应该使用Parallel.For()有疑问。我做了一个简单的测试,它强烈反对并行化。在什么情况下以及如何正确使用Parallel.For()和PLinq?这是我的测试代码:

class Wrapper
{
    public void Sequential()
    {
        Stopwatch sw = Stopwatch.StartNew();

        for (int i = 0; i < 1000; i++)
        {
            DauntingOp(i);
            DauntingOp(i + 9000);
            DauntingOp(i - 8521);
            DauntingOp(i);
            DauntingOp(i + 9000);
            DauntingOp(i - 8521);
        }

        Console.WriteLine("For = ms: {0}", sw.ElapsedMilliseconds);
    }

    public void ParallelFor()
    {
        Stopwatch sw = Stopwatch.StartNew();

        Parallel.For(0, 1000, (elem) => 
        {
            DauntingOp(elem);
            DauntingOp(elem + 9000);
            DauntingOp(elem - 8521);
            DauntingOp(elem);
            DauntingOp(elem + 9000);
            DauntingOp(elem - 8521);
        });

        Console.WriteLine("Parallel For = ms: {0}", sw.ElapsedMilliseconds);
    }

    private void DauntingOp(int index)
    {
        try
        {
            long val = index;
            for (int i = 0; i < 1000; i++)
            {
                long a = val + 345678;
                long b = a + 4567;
                long c = a - b;
                long d = long.Parse(new Random().Next().ToString());
                long x = d - a - b - c;
                long y = long.Parse(new Random().Next().ToString()) - (long.Parse(new Random().NextDouble().ToString()) + 345 - x);
            }
        }
        catch { }
        finally
        {
            try
            {
                long a = 345678;
                long b = a + 4567;
                long c = a - b;
                long d = long.Parse(new Random().Next().ToString());
                long x = d - a - b - c;
                long y = long.Parse(new Random().Next().ToString()) - (long.Parse(new Random().Next().ToString()) + 345 - x);
            }
            catch { }
        }
    }

}

class Program
{
    static void Main(string[] args)
    {
        Wrapper wrapper = new Wrapper();
        wrapper.Sequential();
        wrapper.ParallelFor();

        Console.Read();
    }
}

结果:

For = ms: 22645
Parallel For = ms: 29020

不应该是Parallel.For更快?

1 个答案:

答案 0 :(得分:0)

在发布模式下运行解决方案,无需调试。

我的系统有四个核心,我可以使用任务管理器查看:

enter image description here

基准测试的可靠性要快四倍:

enter image description here

请注意,默认情况下,您在Windows 10中未启用多个核心。您必须从“开始”菜单运行msconfig,并在“启动”菜单中启用多个处理器:

enter image description here