DateTime Ticks/Milliseconds Question (possibly Thread.Sleep () related - ?)

  • Thread starter Thread starter Mr Bounce
  • Start date Start date
M

Mr Bounce

Hi,

Slightly dim question, possibly. I dunno. When i run the following c#:

for (int i = 0; i < 100; i++)
{
System.Diagnostics.Debug.WriteLine
(DateTime.Now.Millisecond.ToString ());
System.Threading.Thread.Sleep (1);
}

I would expect the output to increment by at least 1 every line (since
I am asking my thread to sleep for 1 millisecond).

The output generated, however, looks like this:

627
409
409
409
424
424
440
440
440
456
456
456
456

(etc)

surely this is impossible?

I also noticed a similar thing when using Ticks instead of Milliseconds

Is there something im missing? I thought maybe it was something i hadnt
encountered before to do with thread scheduling (ie: none others to be
scheduled, so its not sleeping), but if i change the interval to 100ms
there is a visible (and seemigly regular) pause, and the output number
increments by slightly more than 100 each time round.

If anyone can shed some light on this i would be grateful - I'm now
wondering if its something to do with the clock speed of my PC...?

Thanks,

Chris
 
The resolution of the system clock isn't 1/1000 second, but rathter
something like 1/62 second. There is an interrupt that increases an
integer value 62 (?) times a second, this integer value is then
converted to a time value when you use DateTime.Now.

Every time you see the time change, the interrupt has increased the
integer value by one, and that translates to an increase in time of
about 16 ms.
 
The resolution of the system clock isn't 1/1000 second, but rathter
something like 1/62 second. There is an interrupt that increases an
integer value 62 (?) times a second, this integer value is then
converted to a time value when you use DateTime.Now.

Every time you see the time change, the interrupt has increased the
integer value by one, and that translates to an increase in time of
about 16 ms.


ah - got it.

thanks very much,

chris
 
On some older systems, if you do the same test, you will get increments of
52 milliseconds. The original PC clock was configured to interrupt the
processor 18.2 times a second. (I have no idea why IBM chose that
frequency.)

Mike Ober.
 
On some older systems, if you do the same test, you will get increments of
52 milliseconds. The original PC clock was configured to interrupt the
processor 18.2 times a second. (I have no idea why IBM chose that
frequency.)

I don't remember the details but my recollection is that IBM chose a
clock speed of 4.77 MHz because it was easy to use that clock speed to
derive the frequencies necessary to drive a standard TV monitor
horizontal sweep frequency. The 18.2/second tick rate was then a
convenient subfrequency of that value.
 
Back
Top