2016-12-26 108 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

我很抱歉,如果我說明了這個非常明顯的問題,但是您在更改啓動選項後確實重啓了,對吧? –