Danegraphics
Danegraphics

Reputation: 477

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

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!

Upvotes: 6

Views: 18214

Answers (2)

Nav E
Nav E

Reputation: 11

using (PerformanceCounter system_cpu_usage = new PerformanceCounter("Processor", "% Processor Time", "_Total"))
            {
                var first = system_cpu_usage.NextValue();
                Thread.Sleep(2500);
                // Do something
                
            }

You MUST include a var first = system_cpu_usage.NextValue(); in order to then proceed with displaying the actual value.

Upvotes: 0

L_J
L_J

Reputation: 2439

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();
}

Upvotes: 8

Related Questions