秒表与使用 System.DateTime.Now 进行计时事件 [英] Stopwatch vs. using System.DateTime.Now for timing events
问题描述
我想跟踪我的代码的性能,所以我使用 System.DateTime.Now
存储了开始和结束时间.我将两者之间的差异作为我的代码执行时间.
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.
但我注意到差异似乎并不准确.所以我尝试使用 Stopwatch
对象.结果证明这要准确得多.
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.
谁能告诉我为什么 Stopwatch
比使用 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:
秒表通过计算底层计时器机制中的计时器滴答来测量经过的时间.如果安装的硬件和操作系统支持高分辨率性能计数器,则 Stopwatch 类使用该计数器来测量经过的时间.否则,秒表类使用系统计时器来测量经过的时间.使用 Frequency 和 IsHighResolution 字段来确定秒表计时实现的精度和分辨率.
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.
它使用比 DateTime.Now
更高的分辨率/精度.
It uses a higher resolution / precision than DateTime.Now
.
您还可以查看这些相关链接:
You can also check out these related links:
Environment.TickCount vs DateTime.Now
DateTime
已经足够精确到秒,但我会推荐 StopWatch
.
DateTime
is good enough for precision to the second probably but anything beyond that I would recommend StopWatch
.
这篇关于秒表与使用 System.DateTime.Now 进行计时事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!