BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

System Information
.NET 1.1+

Getting the System Up Time

Sometimes it is necessary to know how much time has passed since Windows was started. This article demonstrates two ways to obtain this information using the .NET framework and describes the limitations of one of the commonly used methods.

Obtaining the System Up Time

There are several ways in which to determine how long Windows has been running, known as the system's up time. In this article we will look at two methods that use only managed code.

Using the Environment Class to Get the Up Time

The Environment class is found in the System namespace. It allows you to obtain information about the operating system and the current execution environment through a set of static methods and properties. The TickCount property of the Environment class returns the number of milliseconds since the system was started. This can easily be converted into a TimeSpan structure using the static FromMilliseconds method.

TimeSpan ts = TimeSpan.FromMilliseconds(Environment.TickCount);
Console.WriteLine("{0}d {1}h {2}m {3}s", ts.Days, ts.Hours, ts.Minutes, ts.Seconds);

Limitations

The main limitation with the TickCount property is that is returns a 32-bit signed integer value. This means that the largest value that can be returned represents approximately twenty-five days. After this, the value overflows and restarts at the largest possible negative value. The TickCount is, therefore, useful only for machines that are not permanently switched on.

Using a Performance Counter to Get the Up Time

The second method that we will consider for obtaining the up time is to read the "System Up Time" performance counter. This counter returns the up time as a floating-point value containing a number of seconds. The value is precise to seven digits, allowing you to obtain fractions of a second for low values but with decreasing accuracy for higher values. However, as the float data type allows very large values to be stored, reading the performance counter does not have the twenty-five day limitation.

To simplify the code for reading a performance counter, add the following using directive:

using System.Diagnostics;

The System Up Time counter is a two-read counter in the System category. The first time that the PerformanceCounter's NextValue method is called it will return zero. Subsequent calls return the correct value.

PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time");
upTime.NextValue();
TimeSpan ts = TimeSpan.FromSeconds(upTime.NextValue());
Console.WriteLine("{0}d {1}h {2}m {3}s", ts.Days, ts.Hours, ts.Minutes, ts.Seconds);
17 January 2010