2016-12-26 71 views
-1

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

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更快?

+0

我要说的是,管理并行循环的成本outweighing工作的成本在这种情况下,正在做。如果你正在做的事情需要更长时间,例如连接到数据库并在事务中插入一些记录,那么你可能会发现并行循环更快。顺便说一句,对于将i + 9000传递给DauntingOp的情况,该方法不会在try中执行任何操作,因为index已经是1000+,因此这些调用不会为您的测试添加任何有意义的内容。 – DeanOC

+0

我在你的机器上运行你的代码,差异很小。我刚刚启用了多个内核;我会重新启动并重试,然后再回到你身边。 –

+1

这取决于您的CPU有多少个内核。如果它的单核心然后并行的将由于线程上下文切换的开销而工作得更慢。 – serhiyb

回答

0

在发布模式下运行解决方案而不进行调试。

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

enter image description here

和基准是可靠的四倍:

enter image description here

注意,你赢了” t默认情况下在Windows 10中启用了多个内核。你必须从你的开始菜单运行msconfig,并启用多个处理器在启动菜单:

enter image description here

+0

这很奇怪。引导选项我切换了8个处理器的数量。我的处理器是i7 3632QM 2.2GHz - 4/8核心。我使用调试器以释放模式运行程序 - 类似的结果。但是没有调试器的发布模式: –

+0

Parallel For = ms:18 For = ms:29 –

+0

我很抱歉,如果我说明了这个非常明显的问题,但是您在更改启动选项后确实重启了,对吧? –