How to get total CPU usage (all processes)? (C#)

11,766

When you use the PerformanceCounter class the first call of the NextValue() method most likely will return 0. So, you should call it a few times after some delay to get an appropriate measure.

you will need:

using System.Diagnostics;
using System.Threading;

Then you can obtain it as follows:

static void Main(string[] args)
{
    var cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    Thread.Sleep(1000);
    var firstCall = cpuUsage.NextValue();

    for (int i = 0; i < 5; i++)
    {
        Thread.Sleep(1000);
        Console.WriteLine(cpuUsage.NextValue() + "%");
    }

    Console.Read();
}
Share:
11,766
Danegraphics
Author by

Danegraphics

Updated on June 09, 2022

Comments

  • Danegraphics
    Danegraphics almost 2 years

    In a windows application, how do I get the TOTAL current CPU usage of ALL processes (not just one process or application) on ALL cores in C#? (without using any third party libraries, if possible)

    I could only find questions and answers about the CPU usage of a single process. For example this one appears to ask for the CPU usage of just the running program, and the answers are unclear about what information their code gathers, so it's not very helpful in this instance.

    Though, if this question is answered somewhere else, I will happily accept a link.

    Thank you!

  • Danegraphics
    Danegraphics almost 6 years
    That first call of NextValue() thing was super helpful! Thank you!
  • honzakuzel1989
    honzakuzel1989 about 3 years
    The values look like approx the half in comparison with task manager on my computer.. Strange.
  • Danegraphics
    Danegraphics about 3 years
    The first answer already contains this information, but thank you for making sure!
  • jjxtra
    jjxtra about 2 years
    Also seeing this, not sure what is going on...