使用System.DateTime.Now定时事件与秒表 [英] Stopwatch vs. using System.DateTime.Now for timing events

查看:121
本文介绍了使用System.DateTime.Now定时事件与秒表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,所以我使用存储在开始和结束的时间来跟踪我的code的性能 System.DateTime.Now 。我把两者之间的差异随着时间的我的code来执行。

I wanted to track the performance of my code so I stored the start and end time using System.DateTime.Now. I took the difference between the two as the time my code to execute.

我注意到,虽然这种差异并未以准确。所以我试图用一个秒表对象。事实证明,这是很多,更精确。

I noticed though that the difference didn't appear to be accurate. So I tried using a Stopwatch object. This turned out to be much, much more accurate.

谁能告诉我,为什么秒表会比使用计算开始和结束时间之间的差异更准确 System.DateTime.Now

Can anyone tell me why Stopwatch would be more accurate than calculating the difference between a start and end time using System.DateTime.Now?

顺便说一句,我不是在谈论的一个百分之零点。我得到一个15-20%的差异。

BTW, I'm not talking about a tenths of a percent. I get about a 15-20% difference.

推荐答案

根据 MSDN

通过计算计时器秒表测量经过时间刻度底层定时器机制。如果安装的硬件和操作系统支持高分辨率性能计数器,然后秒表类使用计数器测量经过时间。否则,S​​topwatch类使用系统计时器测量经过的时间。使用频率和IsHighResolution字段,以确定秒表计时执行precision和分辨率。

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

它采用了更高分辨率/ precision比 DateTime.Now

It uses a higher resolution / precision than DateTime.Now.

您还可以检查出这些相关链接:

You can also check out these related links:

<一个href=\"http://stackoverflow.com/questions/243351/environment-tickcount-vs-datetime-now\">http://stackoverflow.com/questions/243351/environment-tickcount-vs-datetime-now

<一个href=\"http://stackoverflow.com/questions/28637/is-datetime-now-the-best-way-to-measure-a-functions-performance\">http://stackoverflow.com/questions/28637/is-datetime-now-the-best-way-to-measure-a-functions-performance

的DateTime 是precision第二个可能,但任何超出我会建议不够好秒表

DateTime is good enough for precision to the second probably but anything beyond that I would recommend StopWatch.

这篇关于使用System.DateTime.Now定时事件与秒表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆