2013-03-16 104 views
3

我正在計算定期由下面的代碼文件的MD5散列。這些文件大約是10MB。 當我以調試模式(Debug | x64)運行我的程序時,對ComputeHash()的調用需要35ms,如果以Release模式(Release | x64)構建,則需要400ms--兩個測試都沒有附加調試器,測試的時間很短。發佈輸出比調試慢:MD5CryptoServiceProvider.ComputeHash()

(我試過用visual studio express 2010和2012 - 結果相同)。

如何在Release模式下獲得良好的Debug-Preformance?有任何想法嗎? 在此先感謝!

代碼:

public static string GetMD5HashFromFile(string fileName) 
{ 
    StringBuilder sb = new StringBuilder(); 

    if (File.Exists(fileName)) 
    { 
    var stream = File.Open(fileName, FileMode.Open, FileAccess.Read, IO.FileShare.ReadWrite); 
    MD5 md5 = MD5.Create(); 

    //for benchmarking 
    var s = Stopwatch.StartNew(); 

    byte[] retVal = md5.ComputeHash(stream); 

    //for benchmarking 
    System.Windows.MessageBox.Show(s.ElapsedMilliseconds.ToString()); 

    stream.Close(); 

    for (int i = 0; i < retVal.Length; i++) 
     sb.Append(retVal[i].ToString("x2")); 
    } 

    return sb.ToString(); 
} 
+0

我在visual studio 2008上測試過,對我來說調試和發佈模式的性能差不多! – 2013-03-16 19:41:27

+0

不要使用'Stopwatch' - 嘗試使用'DateTime'對象並減去時間差。在上面 - 我不知道 – 2013-03-16 19:54:53

+0

@AppDeveloper你使用了什麼文件?一個「隨機」10兆文件? – 2013-03-16 19:56:25

回答

0

你運行通過Visual Studio中的發佈和調試版本?如果是這樣,請嘗試直接在Visual Studio之外運行它們。通過Visual Studio運行它們將始終將調試器附加到您的過程中,導致速度變慢。

+0

進行性能檢查時,我總是使用優化版本並單獨運行程序(不附帶調試器)。 – user2177774 2013-07-21 18:53:01