Environment.TickCount: Int32 (aka SIGNED integer)

Did you know that Environtment.TickCount returns a signed 32 bit integer? Did you know the sign on this property flips every 24.9 days? 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. Ouch! Good thing windows updates get pushed once a month (and generally kindly coerce you to reboot); you might not notice the couple of days at the end when you're pulling negative numbers. But alas, today the negative tickcount decided to hit me. I was running unittests and noticed I was sending out negative request numbers?!? WTF! ROTFL! :) A little investigation turned up the culprit; trusty old TickCount wasn't that trusty after all. (That will teach me for stopping the windows update service to stop the reboot nagging, right?)
What happened to the days when you could boast about your system uptime? My linux box easily ran into hundreds of days (the resets were caused by power outtages)! What happened to my linux box?!?
What is a developer to do? Eureka! You can cast it to a Uint32! Twice the positive size, twice the fun, right?

UInt32 tickCount = (UInt32)Environment.TickCount;

Nah, you'll still wrap around after 59.8 days, which means you cannot use it to calculate the system uptime or measure time intervals... Here's how to calculate system uptime:

PerformanceCounter uptimeCounter = new PerformanceCounter("System", "System Up Time", true); uptimeCounter.NextValue();// init counter float uptime = uptimeCounter.NextValue(); // get uptime in secs TimeSpan uptimespan = TimeSpan.FromSeconds(uptime); Trace.WriteLine("Uptime: " + uptimespan.ToString());

And this is how you measure a time interval:

Stopwatch sw = new Stopwatch(); sw.Start(); // do lengthy stuff sw.Stop(); Trace.WriteLine("Elapsed: " + sw.Elapsed.ToString());

Enjoy! - Doc. How do YOU determine your system uptime programmatically?

No comments:

Post a Comment

My Latest Track