您的位置:首页 > 编程语言 > C#

C#: 统计method的执行时间

2016-06-13 11:05 411 查看
对于性能分析来说,无非是内存占用,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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息