Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DateTime.Now.Ticks not consistent?

Tags:

c#

datetime

I have a simple console application with the following body:

Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());
Console.WriteLine(DateTime.Now.Ticks.ToString());

And these are the outputs of three different runs:

635258949900018675
635258949900028676   // +10001
635258949900028676   // +0
635258949900038677   // +10001
635258949900038677   // +0
635258949900038677   // +0
635258949900038677   // +0
635258949900038677   // +0
635258949900038677   // +0
635258949900038677   // +0

635258949937502423
635258949937512424   // +10001
635258949937512424   // +0
635258949937512424   // +0
635258949937512424   // +0
635258949937522425   // +10001
635258949937522425   // +0
635258949937522425   // +0
635258949937522425   // +0
635258949937522425   // +0

635258961813519906
635258961813529907   // +10001
635258961813529907   // +0
635258961813529907   // +0
635258961813529907   // +0
635258961813539908   // +10001
635258961813539908   // +0
635258961813539908   // +0
635258961813539908   // +0
635258961813539908   // +0

One might guess it is normal for these values to be different since it takes time between Console.WriteLine executions. The interval between the lines is a constant value of 10001, but somehow this value is not added to the previous one at EVERY step. Sometimes it is, sometimes it is not. I am wondering why this happens.

like image 991
anar khalilov Avatar asked Oct 02 '22 19:10

anar khalilov


1 Answers

Eric Lippert has an excellent article about this topic. Key quote:

The purpose of the “wall clock” timer is to produce dates and times for typical real-world uses, like “what time does Doctor Who start?” or “when do we change to daylight savings time?” or “show me the documents I edited last Thursday after lunch.” These are not operations that require submicrosecond accuracy.

like image 200
Dio F Avatar answered Oct 05 '22 13:10

Dio F