2014-09-03 74 views
0

我們正在研究兩個不同的庫,它們往往會執行相同的工作。我已經被分配來檢查哪個庫在給定的輸入集合下更快地執行相同的工作。有多個測試用例可以確定這一點,我想檢查庫執行任務需要多少時間(以毫秒爲單位)。檢查C#代碼的性能的最佳方法

以下是代碼的概要。

// preparation of input parameters 
// Get the timestamp 
// Calling the desired library with the set of input parameters 
// again get the timestamp 
// Process the output received from the library 

// get a diff between timestamp and write it into a file. 

我應該做的在C#中,並閱讀了一些提供文檔和一些網上搜索,我想出了下面的代碼可用於測量

int s1 = DateTime.Now.Millisecond; 
int e1 = DateTime.Now.Millisecond; 
int f1 = e1 - s1; 
FileStream fs = new FileStream("Time_Diff.txt", FileMode.Append); 
StreamWriter sw = new StreamWriter(fs); 
string str = Convert.ToString(f1); 
sw.WriteLine(str); 
sw.WriteLine(e1 + " " + s1); 
sw.Flush(); 
sw.Close(); 
採取(以毫秒爲單位)的時間

我只是想知道我正朝着正確的方向前進。另外如果有人能夠建議我採用另一種方式來做同樣的事情?

我想知道的另一件事是我可以使用其他實踐方法來確保我們選擇的圖書館能夠提供最佳性能?

另一個小的要求。有人可以讓我知道如何實現秒錶(或任何其他類似的方式來獲得時間戳)在C++中做同樣的事情嗎?

感謝,如下 Azeem

+1

DIFF是不是一個好主意,因爲精度並不好(http://jaychapman.blogspot.co.at/2007/11/datetimenow-precision.html)。 ..使用'秒錶'實例!無論如何,只需使用關鍵字「基準」和「C#」進行復雜的谷歌搜索...或者,只需在此閱讀以下問題就可以了:http://stackoverflow.com/questions/28637/is-datetime-now - 最佳測量方式 - 功能 - 性能 – 2014-09-03 06:21:52

+3

使用['Stopwatch'](http://msdn.microsoft.com/zh-cn/library/system.diagnostics.stopwatch(v = vs。 110).aspx)類而不是'DateTime'。 [相關問題](http://stackoverflow.com/questions/28637/is-datetime-now-the-best-way-to-measure-a-functions-performance)。 – Yuriy 2014-09-03 06:22:38

+0

每次通話需要多長時間?你應該確保你的工作時間很重要 - 這可能意味着撥打數千或數百萬次的電話。 – 2014-09-03 06:22:49

回答

2

使用秒錶。 `DateTime`-實例之間

 var stopWatch = System.Diagnostics.Stopwatch.StartNew(); 
     FileStream fs = new FileStream("Time_Diff.txt", FileMode.Append); 
     StreamWriter sw = new StreamWriter(fs); 
     //Total time required 
     sw.WriteLine("\nTotal time: " + stopWatch.Elapsed.TotalSeconds.ToString()); 
     sw.Flush(); 
     sw.Close(); 
相關問題