get system cpu usage in csharp

Here is a C# code snippet to get the current CPU usage of the system using the PerformanceCounter class from the System.Diagnostics namespace:

main.cs
using System.Diagnostics;

public static float GetCpuUsage()
{
    var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
    cpuCounter.NextValue();
    System.Threading.Thread.Sleep(1000);
    return cpuCounter.NextValue();
}
263 chars
10 lines

Explanation:

  • PerformanceCounter is a class that provides access to Windows performance counters. We create a new instance of the PerformanceCounter class, specifying the Processor category, the % Processor Time counter, and "_Total" instance (meaning all processors).
  • We call cpuCounter.NextValue() twice: the first time to initialize the counter and the second time to get the current usage value. There is a delay of 1 second between these calls to allow the counter to update.
  • The method returns the CPU usage as a float value. Multiply by 100 to get the percentage value.

gistlibby LogSnag