tags:

views:

132

answers:

2

I'm curious as to how the .NET BCL property Environment.TickCount is implemented. In particular I'd like to now if it is affected by system time adjustments.

My first guess as to how the property was implemented was that it was simply a managed wrapper around the GetTickCount method. However, the documentation for the GetTickCount method states that it is affected by adjustments made by the GetSystemTimeAdjustment function but the documentation for Environment.TickCount does not mention anything about time adjustments.

I'm trying to figure out if the Environment.TickCount can be used as a (albeit low-precision) consistently increasing time value.

+1  A: 

No, it's not affected by system time adjustments.

Whether it's suitable for a "consistently increasing time value" depends on your exact requirements. From the MSDN documentation:

The value of this property is derived from the system timer and is stored as a 32-bit signed integer. Consequently, if the system runs continuously, TickCount will increment from zero to Int32.MaxValue for approximately 24.9 days, then jump to Int32.MinValue, which is a negative number, then increment back to zero during the next 24.9 days.

LukeH
+2  A: 

No, Environment.TickCount is not affected by adjustments of the system time. That was my interpretation of the documentation, but my curiosity demanded harder proof, so I had the following code run while adjusting the system back and forth one hour:

while (true)
{
    Console.WriteLine(Environment.TickCount);
    Thread.Sleep(1000); 
}

...and the output showed a perfect sequence that was not affected by the time adjustments.

Update
So I did some more homework, triggered by Marcus' question in the comments below. I am quite sure (could not confirm though) that Environment.TickCount makes a call to GetTickCount that has the following mentioned in the docs:

The resolution of the GetTickCount function is limited to the resolution of the system timer, which is typically in the range of 10 milliseconds to 16 milliseconds. The resolution of the GetTickCount function is also affected by adjustments made by the GetSystemTimeAdjustment function.

So, while it is not affected by altering the system time, it seems that will be affected by adjustments that are caused by a call to SetSystemTimeAdjustment.

Fredrik Mörk
(lang:sv Tack!) Hey thanks, just curious though. Are you certain that system time adjustments (the incremental scary type described in the GetSystemTimeAdjustment docs where time runs faster or slower to catch up) really takes place when you set the time manually? Doesn't the system time simply jump to the correct time directly when you do that?
Markus Olsson