How to calculate the CPU Usage Programmatically using C#

Feb 9, 2010 Posted by Lara Kannan
Question is...
How to calculate the CPU Usage Programmatically using C#

The PerformanceCounter class represents a WindowsNT performance counter component. To read from a performance counter, we first create an instance of the PerformanceCounter class supplying the CategoryName, CounterName, and InstanceName as parameters to the constructor and then call the NextValue() method to take a performance counter reading.

Import the namespaces System.Diagnostics and System.Threading.


static PerformanceCounter cpuUsage;
public static void Main(string[] args)
{
cpuUsage =
new PerformanceCounter("Processor", "% Processor Time", "_Total");

Console.WriteLine(cpuUsage.NextValue() + " %");
Thread.Sleep(1000);

Console.WriteLine(cpuUsage.NextValue() + " %");
Console.Read();
}

Note:
Observe that we are calling NextValues() twice and after a delay of 1 second. This is because performance counters need two samples to perform the calculation and the counter value is updated once per second, hence the 1 second delay between the two calls.

Share
Labels:

Post a Comment