Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting CPU usage of a process in C#

Tags:

c#

I would like to get CPU usage for a specific process..

This code

total_cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");

works great. The number is corresponding to the "CPU usage" number in Windows' Task Manager.

But the following gives me weird numbers...

process_cpu = new PerformanceCounter("Process", "% Processor Time", "gta_sa");
var process_cpu_usage = (total_cpu_usage.NextValue() / 100) * process_cpu.NextValue();

As you can see on the screenshot (instead of "7", I am getting "2,9..").

Processes

like image 276
Marek Javůrek Avatar asked Feb 13 '12 11:02

Marek Javůrek


People also ask

How is CPU usage calculated in C?

CpuUsage = 100-100*(Idle - Idle[n])/(KernelAndUser - KernelAndUser[n]); where: CpuUsage is CPU usage as a percentage of the total interval time.


1 Answers

Actually, the Process\% Processor Time\Instance counter returns the % of time that the monitored process uses on % User time for a single processor. So the limit is 100% * the number of processors you have.

There doesn't seem to be an easy way to compute the value that taskmgr displays using perfmon counters. See this link.

Also remember the percentage of CPU usage is not a fixed value, but a calculated value:

((total processor time at time T2) - (total processor time at time T1) / (T2 - T1))

This means that the values depend on both T2 and T1, so there might be differences between what you see on task manager and what you compute, if T2 and T1 used by Task Manager are slightly different than T2 and T1 used by your program.


If you are interested, I can provide you some code to retrieve this value using P/Invoke. But'll loose the benefits of Performance Counters (such as monitoring remote processes).

like image 71
ken2k Avatar answered Sep 21 '22 19:09

ken2k