Recommended method to calculate the difference between two timespans

﹥>﹥吖頭↗ 提交于 2019-12-13 09:21:57

问题


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

Note: perfClock is DateTime (set prior to task)

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


回答1:


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

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

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).

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)




回答2:


I don't know the context in which you are measuring time but it would be good to start of with Stopwatch and check your results.

Also worth a read Precise Measurement




回答3:


Have you tried:

TimeSpan diff = DateTime.Now.Subtract(_perfClock);


来源:https://stackoverflow.com/questions/8754018/recommended-method-to-calculate-the-difference-between-two-timespans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!