Getting CPU Usage in 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 corresponds 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 in the screenshot (instead of "7", I get "2.9 ..").

Processes

+7
source share
2 answers

In fact, Process \% Processor Time \ Instance counter returns% of the time that the monitored process uses for% User time for one processor. Thus, the limit is 100% * the number of processors that you have.

There seems to be no easy way to calculate the value that taskmgr displays using perfmon counters. See this link .

Also remember that 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 T2 and T1, so there may be differences between what you see in the task manager and what you calculate if T2 and T1 used by the task manager are slightly different from T2 and T1 used by your program.


If you are interested, I can provide you with code to retrieve this value using P / Invoke. But you will lose the benefits of performance counters (for example, monitoring remote processes).

+11
source

The division by processor / number of cores is what seems to give fairly accurate results when compared with the task manager.

To save people time:

 // This will return the process usage as a percent of total processor utilisation. var processUsage = process_cpu_usage/nextValue() / Environment.ProcessorCount; 
+6
source

All Articles