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
比较容易混淆的是,貌似使用DateTime.Now的代码也能得到结果,那为啥不用DateTime.Now呢?原因是,DateTime.Now因为涉及Timezone, DST(daylight saving time 夏令时)等计算,通常慢于DateTime.UtcNow。而DateTime.UtcNow则一般需要15ms的频率。
值得注意的是,Stopwatch类也可能使用DateTime.UtcNow,如果当前的机器没有一个高频率的计数器(Stopwatch.IsHighResolution属性可以查看当前机器是否符合),那么Stopwatch会调用DateTime.UtcNow。
是为之记。
Alva Chien
2016.6.13
那么,对于执行时间(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
相关文章推荐
- c#调用COM组件
- 选定虚拟主机 性能凸显优势
- 修改一行代码提升 Postgres 性能 100 倍
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#实现给图片加水印的方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#中的delegate委托类型基本学习教程
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- 举例讲解C#中自动实现的属性
- C#中this的用法集锦
- C#数据结构之顺序表(SeqList)实例详解
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法