C#: 統計method的執行時間

對於性能分析來說,無非是內存佔用,CPU使用和執行時間。

那麼,對於執行時間(elapsed times)的測量,需要強調的是,儘量不要使用DateTime類來,而是應該使用Stopwatch 類。MSDN文檔:https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx

var watch = System.Diagnostics.Stopwatch.StartNew();
// The call to your methods go here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

比較容易混淆的是,貌似使用DateTime.Now的代碼也能得到結果,那爲啥不用DateTime.Now呢?原因是,DateTime.Now因爲涉及Timezone, DST(daylight saving time 夏令時)等計算,通常慢於DateTime.UtcNow。而DateTime.UtcNow則一般需要15ms的頻率。

DateTime startTime = DateTime.Now;
// The call to your methods go here
DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);

值得注意的是,Stopwatch類也可能使用DateTime.UtcNow,如果當前的機器沒有一個高頻率的計數器(Stopwatch.IsHighResolution屬性可以查看當前機器是否符合),那麼Stopwatch會調用DateTime.UtcNow。

是爲之記。
Alva Chien
2016.6.13

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章