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

 

posted @ 2016-06-13 11:06  会拍照能修图的码农  阅读(129)  评论(0)    收藏  举报