How to calculate the difference between two DateTime in ms?

By the value of msdn DateTime, the accuracy is 10 ms. The accuracy of t2-t1 in the example below is also 10 ms. However, the return value is "double", which is confusing.

 DateTime t1 = DateTime.Now; // precision is 10 ms .... DateTime t2 = DateTime.Now; // precision is 10 ms ... (t2-t1).TotalMilliseconds; // double (so precision is less than 1 ms???) 

I expect an int value because a double value does not make sense when the accuracy is 10 ms. I need to use the given value in Thread.Sleep (). Should I just use int?

+4
source share
1 answer

The accuracy of DateTime itself comes down to a tick.

The granularity of DateTime.Now usually 10 or 15 ms - this is the granularity of the system clock. (This does not mean that the clock is accurate to the nearest 10 or 15 ms, mind you.) The subtraction operator on DateTime does not need to know or care about this, although the result is just a TimeSpan , which again is accurate to the tick level.

A simple click on int should be absolutely accurate.

(Perhaps you can read Eric Lippert's blog post .

+7
source

Source: https://habr.com/ru/post/1385846/


All Articles