How to get total CPU usage (all processes)? (C#)
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();
}
Danegraphics
Updated on June 09, 2022Comments
-
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 almost 6 yearsThat first call of
NextValue()
thing was super helpful! Thank you! -
honzakuzel1989 about 3 yearsThe values look like approx the half in comparison with task manager on my computer.. Strange.
-
Danegraphics about 3 yearsThe first answer already contains this information, but thank you for making sure!
-
jjxtra about 2 yearsAlso seeing this, not sure what is going on...