在 C# 中获取进程的 CPU 使用率
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9259772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting CPU usage of a process in C#
提问by Marek Jav?rek
I would like to get CPU usage for a specific process..
我想获取特定进程的 CPU 使用率..
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.
效果很好。该数字对应于 Windows任务管理器中的“CPU 使用率”数字。
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..").
正如您在屏幕截图中看到的(而不是“7”,我得到的是“2,9..”)。


采纳答案by ken2k
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.
实际上,Process\% Processor Time\Instance 计数器返回受监视进程在 % User time 上用于单个处理器的时间百分比。所以限制是 100% * 您拥有的处理器数量。
There doesn't seem to be an easy way to compute the value that taskmgrdisplays using perfmon counters. See this link.
似乎没有一种简单的方法来计算taskmgr使用 perfmon 计数器显示的值。请参阅此链接。
Also remember the percentage of CPU usage is not a fixed value, but a calculated value:
还要记住 CPU 使用率的百分比不是一个固定值,而是一个计算值:
((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.
这意味着这些值取决于 T2 和 T1,因此如果任务管理器使用的 T2 和 T1 与程序使用的 T2 和 T1 略有不同,那么您在任务管理器上看到的内容与您计算的内容之间可能存在差异。
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).
如果您有兴趣,我可以为您提供一些代码来使用 P/Invoke 检索此值。但是会失去性能计数器的好处(例如监视远程进程)。
回答by Joshua Hayes
Dividing by the processor/core countis what seemed to yield fairly accurate results when comparing against 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;

