使用性能计数器的任务管理器中的CPU使用率

时间:2016-02-09 09:55:09

标签: c# windows performance cpu-usage performancecounter

[我的尝试]

已经完成了

  1. How to get the CPU Usage in C#? 但是" _Total"处理器实例将给我总CPU消耗,而不是特定应用程序或'过程'

  2. In a C# Program, I am trying to get the CPU usage percentage of the application but it always shows 100

  3. What exactly is CPU Time in task manager?,解释了它,但没有说明如何检索此值。

  4. 在提及http://social.technet.microsoft.com/wiki/contents/articles/12984.understanding-processor-processor-time-and-process-processor-time.aspx

    之后

    我明白了

    TotalProcessorTimeCounter = new PerformanceCounter("Process", "% Processor Time", processName);
    

    的基线为(逻辑CPU数量* 100) 基本上,这并没有给我100%的CPU消耗。

    尝试挖掘任务管理器,发现任务管理器 - >处理器 - > CPU使用率为100。

    Processor \%Processor Time对象不将进程名称作为输入。它只有' _Total'作为输入。

    [问题]

    对于多核系统的特定进程,如何使用超过100的性能计数器获取此数据(CPU消耗)?

3 个答案:

答案 0 :(得分:3)

在阅读此性能计数器文档https://social.technet.microsoft.com/wiki/contents/articles/12984.understanding-processor-processor-time-and-process-processor-time.aspx后,我意识到获取此值的正确方法实际上是取100并减去所有处理器的空闲时间。

  

%Processor Time是处理器执行非空闲线程所花费的时间百分比。

var allIdle = new PerformanceCounter(
    "Processor", 
    "% Idle Time", 
    "_Total"
);

int cpu = 100 - allIdle;

这给出的值非常接近任务管理器显示的值,并且由于四舍五入或轮询计数器的具体时间,可能在某些点上不同。

答案 1 :(得分:2)

这为我提供了你在任务管理器上获得的确切数字(在Details标签中),这是你想要的吗?

// Declare the counter somewhere
var process_cpu = new PerformanceCounter(
                                   "Process", 
                                   "% Processor Time", 
                                   Process.GetCurrentProcess().ProcessName
                                        );
// Read periodically
var processUsage = process_cpu.NextValue() / Environment.ProcessorCount;

答案 2 :(得分:1)

如果使用此选项,则可以通过任务管理器获得相同的结果:

cpuCounter = new PerformanceCounter(
        "Processor Information",
        "% Processor Utility",
        "_Total",
        true
    );