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..").
CpuUsage = 100-100*(Idle - Idle[n])/(KernelAndUser - KernelAndUser[n]); where: CpuUsage is CPU usage as a percentage of the total interval time.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With