Eric Bergman-Terrell's Blog

.NET Programming Tip: How to Determine System Uptime Without Overflow Issues
October 4, 2010

You can try to use Environment.TickCount to determine how long ago a machine was started. But Environment.TickCount returns a 32-bit signed integer which can overflow for systems that stay up for days at a time.

To avoid this overflow problem, you can query the "System Up Time" performance counter:

public TimeSpan SystemUpTime()
{
  PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time");

  // You've got to call this twice. First time it returns 0 and the second time it returns the real info.
  upTime.NextValue();
   
  return TimeSpan.FromSeconds(upTime.NextValue());
}

Caveat: if your software runs with limited privileges you may not be able to query the performance counter. For example, I run my website on a shared server, and it's not allowed to query this performance counter :-(.

This tip is based on a newsgroup posting by Stoitcho Goutsev.

Keywords: Environment.TickCount, Uptim, Performance Counter

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015
Node.js / Express Programming Tip: Detect and Fix Memory LeaksOctober 27, 2015