我想获取特定进程的 CPU 使用情况。
这段代码
total_cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
效果很好。该数字对应于 Windows 中的“CPU 使用率”数字任务管理器 http://en.wikipedia.org/wiki/Windows_Task_Manager.
但下面给了我奇怪的数字......
process_cpu = new PerformanceCounter("Process", "% Processor Time", "gta_sa");
var process_cpu_usage = (total_cpu_usage.NextValue() / 100) * process_cpu.NextValue();
正如您在屏幕截图中看到的(我得到的不是“7”,而是“2,9..”)。
实际上,Process\% Processor Time\Instance 计数器返回受监控进程在单个处理器的“用户时间百分比”上使用的时间百分比。所以限制是 100% * 您拥有的处理器数量。
似乎没有一种简单的方法来计算该值taskmgr http://en.wikipedia.org/wiki/Windows_Task_Manager使用 perfmon 计数器显示。看这个链接 https://serverfault.com/questions/83823/perfmon-processor-time-vs-task-managers-cpu-usage.
另请记住 CPU 使用百分比不是固定值,而是计算值:
((total processor time at time T2) - (total processor time at time T1) / (T2 - T1))
这意味着这些值取决于 T2 和 T1,因此,如果任务管理器使用的 T2 和 T1 与程序使用的 T2 和 T1 略有不同,您在任务管理器上看到的内容与您计算的内容之间可能会存在差异。
如果您有兴趣,我可以为您提供一些代码来使用 P/Invoke 检索该值。但会失去性能计数器的好处(例如监视远程进程)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)