简体   繁体   English

PerformanceCounter CPU使用率值始终为0

[英]PerformanceCounter CPU usage value allways 0

For below Performance counter, I am always getting % Processor Time is 0, even my CPU shows 100% usage, what could be the reason? 对于低于性能的计数器,我总是得到%Processor Time为0,即使我的CPU显示100%使用率,这可能是什么原因?

PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
Console.WriteLine(pc.NextValue());

It's explained by the remarks in the NextValue() documentation : 通过NextValue()文档中的备注对此进行了解释:

If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0. 如果计数器的计算值取决于两次计数器读取,则第一次读取操作将返回0.0。 Resetting the performance counter properties to specify a different counter is equivalent to creating a new performance counter, and the first read operation using the new properties returns 0.0. 重置性能计数器属性以指定其他计数器等效于创建新的性能计数器,并且使用新属性进行的第一次读取操作将返回0.0。 The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read. 建议两次调用NextValue方法之间的延迟时间为一秒,以允许计数器执行下一个增量读取。

So if you change your code to something like: 因此,如果您将代码更改为:

while (true)
{
    Console.WriteLine(pc.NextValue());
    Thread.Sleep(1000);
}

... then you'll see appropriate values. ...然后您将看到适当的值。

If you try directly read total time you will always get 0, the reason being is that the PerformanceCounter object needs 2 values to give an accurate reading. 如果您尝试直接读取总时间,您将始终获得0,原因是PerformanceCounter对象需要2个值才能提供准确的读数。

The method below returns an int representing the accurate % of CPU usage at that time. 下面的方法返回一个整数,该整数表示当时的CPU使用率的准确百分比。

while (true)
{
    PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    float tempValue = cpuCounter.NextValue();
    Thread.Sleep(1000);
    Console.WriteLine(cpuCounter.NextValue());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM