Stopwatch与使用System.DateTime.Now进行计时事件 [英] Stopwatch vs. using System.DateTime.Now for timing events

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

问题描述

我想跟踪我的代码的性能,所以我使用 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.

我注意到差异似乎并不准确。所以我尝试使用一个秒表对象。这可以说是非常准确的。

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?

BTW,我不是谈论十分之一的百分点。我得到约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

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

You can also check out these related links:

Environment.TickCount vs DateTime.Now

是DateTime.Now是测量功能性能的最佳方法?

DateTime 对于精度来说足够好到第二个可能,但任何超出我会推荐 StopWatch

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

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

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