2

In C#, if I call DateTime.UtcNow twice in the same process, is it guaranteed that the second call will yield a later time than the first call?

The background is we have an application that logs start time and end time of each task by calling DateTime.UtcNow, and for one task we observed the end time was even earlier than the start time. Of cource our app is complex enough so that before deeper investigation I cannot rule out other possibilities but at least would like to understand if it is by design possible for a later call of DateTime.UtcNow to return an earlier time.

Thanks in advance.

weidi
  • 852
  • 7
  • 20

3 Answers3

6

It can return the same time on a subsequent call, but will only return an earlier time if the system clock has been adjusted, which can happen automatically if the machine synchronizes with a time server.

To time the duration of a task, consider using the Stopwatch class.

Joe
  • 122,218
  • 32
  • 205
  • 338
  • Thanks. one friend also told me about the possibility of system clock being adjusted. Your suggestions are very helpful. – weidi May 05 '16 at 10:18
2

Do you really need DateTime.UtcNow to know when something happened? Or just need to know how long it took? If it is latter, than you should rather use StopWatch

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//your method
stopwatch.Stop();
var howLong = stopwatch.ElapsedMilliseconds;

Some related questions and very good responses here and here.

Community
  • 1
  • 1
Yahya
  • 3,386
  • 3
  • 22
  • 40
0

No. The clock in the computer may jump back in time and two consecutive calls give different results.

I've seen this happen at least due to NTP update and in Virtual Machines.

If you need to keep track of intervals use StopWatch.

gfelisberto
  • 1,655
  • 11
  • 18