Wednesday, October 08, 2008

Sometimes it is better to use DateTime.UtcNow instead of DateTime.Now

When you want to measure how long a certain action takes, you should use DateTime.UtcNow instead of DateTime.Now:

   1: DateTime begin = DateTime.UtcNow;
   2:  
   3: ...
   4:  
   5: DateTime end = DateTime.UtcNow;
   6: MessageBox.Show("Time taken: " + (end-begin).TotalMilliseconds);

Reasons:

  • DateTime.UtcNow is more efficient than DateTime.Now (on my PC: 21 nanoseconds versus 575 nanoseconds).
  • More importantly: DateTime.Now will get you into trouble if Daylight Saving Time is enabled. For instance, it is possible that begin contains 02:59:00 and end contains 02:01:00 (while only two minutes have elapsed).

Of course, both mechanisms are incorrect if the user changes his clock (manually or through synchronziation with a time server).

2 comments:

Anonymous said...

Isn't it better to use a Stopwatch instance for such measurements?

Anonymous said...

Yes, in the given example it probably is, but that is not the point here.