推荐的方法来计算两次次之间的差异 [英] Recommended method to calculate the difference between two timespans

查看:232
本文介绍了推荐的方法来计算两次次之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计算精确到微秒级别的时间差的最佳方法是什么?目前我正在做如下:

What should be the best way to calculate the time diff which is accurate upto the level of Microseconds. currently I am doing as follows:

((TimeSpan)(DateTime.Now - _perfClock)).TotalMilliseconds

注意:perfClock是DateTime(在任务之前设置)

Note: perfClock is DateTime (set prior to task)

这是假定准确度达到毫秒,但在我的情况下,它显示的值以000结尾。像8000,9000等...
这迫使我认为只是将秒转换为毫秒,而不是以毫秒计算差异。 (可能在上面的代码中我错了)

Which is suppose to give accuracy upto Milliseconds, but in my case it is showing values ends with "000". like 8000,9000 etc... This is forcing me to think that is just converting seconds to Milliseconds somewhere, instead of calculating diff in Milliseconds. (Possibly I am wrong somewhere in code above).

但是准确的时差计算应该是推荐的机制?

But what should be the recommended mechanism for accurate Time Diff calculation?

-Sumeet

推荐答案

问题不在于TimeSpan,而是精确到tick,这是100纳秒。

The issue is not with TimeSpan, that is accurate down to ticks, which is 100 nanoseconds.

问题是您正在使用DateTime.Now作为您的计时器。

The issue is you are using DateTime.Now for your timer.

DateTime.Now是准确的16ms我相信如V4Vendetta所提到的,如果需要高分辨率结果,则要使用秒表。秒表可以为您提供蜱虫(长)或TimeSpan。使用Timespan轻松操作(在你的情况下,加/减)。

DateTime.Now is accurate to about 16ms i believe. as mentioned by V4Vendetta, you want to use Stopwatch if you need "high resolution" results. Stopwatch can provide you with ticks (long) or TimeSpan. use Timespan for easy manipulation (in your case, add/subtract).

请注意,秒表提供了一个.IsHighResolution属性,以查看您是否比Datetime更好的准确性。现在(PC iirc总是如此)

Note also that Stopwatch provides a .IsHighResolution property, to see if you have a better accuracy than Datetime.Now (it's always true on PC iirc)

这篇关于推荐的方法来计算两次次之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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