-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」不使用共享資源。
爲什麼時間改變,如果它是相同的文件夾?
並行化不會自動比單線程更快;特別是如果你像訪問單個磁盤一樣訪問單個資源,那麼你將排隊相當多的磁盤隊列等。 –
根據這些圖像的大小以及SealSaver的作用,這可能是I/O限制的 - 在這種情況下,運行更多線程將使它們爭奪磁盤訪問權限。 – Chris
您的第二個(慢)示例使用四個單獨的「圖像」文件夾。他們都一樣嗎? –