Elapsed Time with Environment.TickCount() - Avoiding the wrap

user79755 picture user79755 · Apr 16, 2009 · Viewed 12.1k times · Source

Does the absolute value protect the following code from the Environment.TickCount wrap?

If Math.Abs((Environment.TickCount And Int32.MaxValue) - StartTime) >= Interval Then
    StartTime = Environment.TickCount And Int32.MaxValue ' set up next interval
    ...
    ...
    ...
End If

Is there a better method of guarding against the Environment.TickCount wrap-around?

(This is .NET 1.1.)

Edit - Modified code according to Microsoft Environment.TickCount help.

Answer

Qwertie picture Qwertie · Nov 29, 2009

Avoiding the wrapping problem is easy, provided that the time span you want to measure is no more than 24.8 days (anything longer can't be represented in a signed integer). In C#:

int start = Environment.TickCount;
DoLongRunningOperation();
int elapsedTime = Environment.TickCount - start;

I am not very familiar with VB.NET, but as long as you use unchecked math, this will work and you don't have to worry about the wrap.

For example, if Environment.TickCount wraps from 2147483600 to -2147483596, it doesn't matter. You can still compute the difference between them, which is 100 milliseconds.