Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

c# - Recommended method to calculate the difference between two timespans

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...