High accuracy DateTime.UtcNow

Update: in the original version of this post I’ve jumped to an incorrect conclusion that the timer resolution depends on the operating system. However thanks to a comment from James Manning who has corrected me, I realized that this is likely not related to the OS version (because we’re seeing high resolution DateTime on both Win7 and Windows Server 2008 R2).

I’ve just discovered an interesting thing: apparently one of my machines has timer resolution 1 millisecond or better (as opposed to the typical 15ms that I’m used to seeing elsewhere).

I ran these tests on one machine:

         var dt1 = DateTime.UtcNow;
        Thread.Sleep(11);
        var dt2 = DateTime.UtcNow;
        Console.WriteLine(dt2 - dt1);

It outputs 00:00:00.0156006 (common knowledge – 15-16 milliseconds)

However on my other machine, it outputs: 00:00:00.0110011

Also, I ran this test:

         var sw = Stopwatch.StartNew();
        var start = DateTime.UtcNow;
        int changes = 0;
        int idle = 0;
        while (sw.ElapsedMilliseconds < 50)
        {
            var now = DateTime.UtcNow;
            if (now != start)
            {
                start = now;
                changes++;
            }
            else
            {
                idle++;
            }
        }
 
        var elapsed = sw.Elapsed.ToString();
        Console.WriteLine(elapsed);
        Console.WriteLine(changes);
        Console.WriteLine(idle);

and it printed:

00:00:00.0500000

3

449714

Which means it only updated 3 times within a 50 millisecond interval. On my new machine, this program printed:

00:00:00.0500001

50

471655

Which means that it updated at least every millisecond.