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
EBTCalc Users: A Desktop Version is Now Available!October 25, 2019
Python Script to Audit MediaMonkey TranscodingAugust 15, 2019
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
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