Home > Net >  C# DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() Always Get Same Data in short period
C# DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() Always Get Same Data in short period

Time:08-24

Example Code:
.net core 3

await Task.Delay( 1000 );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

await Task.Delay( 1000 );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

await Task.Delay( 1000 );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

Console.WriteLine( "Hello World!!!!!!!!!"   DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() );

Expect to get different number , but all the same if without any delay.

I wonder how could this happened? testPicture

CodePudding user response:

Windows is not a real-time operating system. It has a system clock resolution of 15.6ms.

The default timer resolution on Windows is 15.6 ms – a timer interrupt 64 times a second.

https://randomascii.wordpress.com/2013/07/08/windows-timer-resolution-megawatts-wasted/#:~:text=The default timer resolution on,consumption and harm battery life.

Your code is running faster than the system updates.

CodePudding user response:

For one the code executes very fast, so that this can indeed all be in the same millisecond between the delays.

However, that is not the only issue. The clock has a certain resolution, which can depend on the platform. On Windows, for instance, resolution is 10..15ms, so that increments are not visible every millisecond.

This is also documented in the documentation for DateTime.UtcNow.

For more exact measurements, have a look at the Stopwatch class.

  • Related