2014-07-23 55 views
-5

我用一個線程運行這個。爲什麼當我運行多線程的方法比較慢?

class Program 
{ 
    static void Main(string[] args) 
    { 
     Thread thread = new Thread(x => beginAnalysis("C:\\Images\\1")); 
     thread.Start(); 
    } 

    public static void beginAnalysis(string folderPath) 
    { 
     Stopwatch sw = new Stopwatch(); 
     sw.Start(); 
     var imagesPath = Directory.GetFiles(folderPath, "*.jpg", SearchOption.AllDirectories); 

     var sealSaver = new ImageProcessingLib.SealSaver(); 

     foreach (string imagePath in imagesPath) 
     { 
      sealSaver.SealSaver(imagePath); 
     } 
     sw.Stop(); 
     Console.WriteLine("Total time: {0}",sw.Elapsed.ToString());Console.ReadKey(); 
    } 
} 

的時間,結果是

總時間:00:00:09.0007113

但是當我運行四個線程的時間是非常不同的

class Program 
{ 
    static void Main(string[] args) 
    { 
     Thread thread = new Thread(x => beginAnalysis("C:\\Images\\1")); 
     thread.Start(); 
     Thread thread2 = new Thread(x => beginAnalysis("C:\\Images\\2")); 
     thread2.Start(); 
     Thread thread3 = new Thread(x => beginAnalysis("C:\\Images\\3")); 
     thread3.Start(); 
     Thread thread4 = new Thread(x => beginAnalysis("C:\\Images\\4")); 
     thread4.Start(); 
    } 

    public static void beginAnalysis(string folderPath) 
    { 
     Stopwatch sw = new Stopwatch(); 
     sw.Start(); 
     var imagesPath = Directory.GetFiles(folderPath, "*.jpg", SearchOption.AllDirectories); 

     var sealSaver = new ImageProcessingLib.SealSaver(); 

     foreach (string imagePath in imagesPath) 
     { 
      sealSaver.SealSaver(imagePath); 
     } 
     sw.Stop(); 
     Console.WriteLine("Total time: {0}",sw.Elapsed.ToString());Console.ReadKey(); 
    } 
} 

的時間結果

Total time: 00:00:12.0002174 

Total time: 00:00:11.0006616 

Total time: 00:00:12.0011639 

Total time: 00:00:13.0006828 

爲什麼時間改變,如果它是相同的文件夾?

這是我的計算機的特點:

操作系統:Windows 8.1中臨 - 64位

RAM:6 GB

處理器:Intel i5-34170 3.20 GHz內核 - 4

Cache L1 256KB - L2 1.0 MB - L3 6.0 MB

我使用framework 4.0和visual studio 2010進行開發

庫「ImageProcessingLib」不使用共享資源。

爲什麼時間改變,如果它是相同的文件夾?

+2

並行化不會自動比單線程更快;特別是如果你像訪問單個磁盤一樣訪問單個資源,那麼你將排隊相當多的磁盤隊列等。 –

+1

根據這些圖像的大小以及SealSaver的作用,這可能是I/O限制的 - 在這種情況下,運行更多線程將使它們爭奪磁盤訪問權限。 – Chris

+0

您的第二個(慢)示例使用四個單獨的「圖像」文件夾。他們都一樣嗎? –

回答

1

有幾個爲什麼你的代碼可以在MT環境運行速度變慢的原因:

  • 運行多線程代碼相比運行單線程增加了管理開銷。通常情況下,您希望執行的代碼的並行化可以彌補它的不足,即在多核系統上整體執行時間減少,每個線程可能會花費相同的時間或可能會花費更長的時間,當你設法點亮所有核心。
  • 你的代碼正在做一些對串行操作(掃描目錄)非常重要的事情。如果你打到同一個目錄,結果很可能會被你的操作系統緩存,但是你打了四個目錄。這意味着你必須等待IO完成每一個操作,而這些操作相互重疊。這對提高性能並不是一個好的方案。

運行代碼的多線程性能方面的原因(而不是,比方說,運行的代碼多線程的,因爲你希望你的用戶界面響應在任何時候)纔有意義,如果沒有共同的瓶頸和操作是完全獨立的。在您的示例中情況並非如此,因爲IO是瓶頸,並且無法在普通計算機上高效並行化,因爲您正在處理磁盤延遲。有許多方法可以改善延遲(更快的磁盤或固態硬盤),但您仍然在處理基本上串行的操作。

相關問題