2014-07-23 57 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是瓶颈,并且无法在普通计算机上高效并行化,因为您正在处理磁盘延迟。有许多方法可以改善延迟(更快的磁盘或固态硬盘),但您仍然在处理基本上串行的操作。

相关问题