秒表与使用 System.DateTime.Now 计时事件
我想跟踪代码的性能,因此我使用 System.DateTime.Now 存储开始和结束时间。我将两者之间的差异作为我的代码执行时间。
但我注意到这种差异似乎并不准确。所以我尝试使用秒表对象。事实证明,这要准确得多。
谁能告诉我为什么Stopwatch
比使用System.DateTime.Now
计算开始时间和结束时间之间的差异更准确?
顺便说一句,我说的不是十分之一。我得到了大约 15-20% 的差异。
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.
Can anyone tell me why Stopwatch
would be more accurate than calculating the difference between a start and end time using System.DateTime.Now
?
BTW, I'm not talking about a tenths of a percent. I get about a 15-20% difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此计时函数性能链接讨论了您的确切问题,特别是本段:
编辑:这听起来像是第二个 DateTime.Now 在与秒表方法结束时不同的时间被调用。
this timing function performance link discusses your exact problem, specifically this paragraph:
EDIT: It kind of sounds like the second DateTime.Now is being called at a different time than when the stopwatch method concludes.
最好使用 Stopwatch 类,因为它比减去 DateTime 值要准确得多:
不幸的是,这段简单的代码在大多数情况下不足以获得准确的测量结果,因为在该类的底层有很多活动在进行。操作系统,它会窃取一些 CPU 时间并减慢代码的执行速度。这就是为什么最好多次执行测试,然后删除最低和最高时间。对于该 puprose,有一个方法可以多次执行测试代码,删除最低和最大时间并计算平均时间,这是一个很好的解决方案。我在我的博客中发布了示例测试方法。
It's better to use the Stopwatch class because it's much more accurate than subtracting DateTime values:
Unfortunately, this simple piece of code won't be enough to get accurate measurements most of the times because there’s a lot of activity going on under the hood of the OS, which can steal some CPU time and slow down the execution of your code. That’s why it is best to execute the tests multiple times and then remove the lowest and the highest times. For that puprose it is a good solution to have a method that executes the tested code multiple times, removes the lowest and the greatest times and calculates the average time. I have published a sample testing method in my blog.
根据 MSDN:
它使用比 DateTime.Now 更高的分辨率/精度。
您还可以查看以下相关链接:
Environment.TickCount 与 DateTime.Now
DateTime.Now 是衡量函数性能的最佳方法?
DateTime
足以精确到秒,但超出此范围我会推荐StopWatch
。As per MSDN:
It uses a higher resolution / precision than
DateTime.Now
.You can also check out these related links:
Environment.TickCount vs DateTime.Now
Is DateTime.Now the best way to measure a function's performance?
DateTime
is good enough for precision to the second probably but anything beyond that I would recommendStopWatch
.