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
.NET Public-Key (Asymmetric) Cryptography DemoJuly 20, 2025
Raspberry Pi 3B+ Photo FrameJune 17, 2025
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021