C# 为什么 cpu 性能计数器一直报告 0% cpu 使用率?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2181828/
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
Why the cpu performance counter kept reporting 0% cpu usage?
提问by smwikipedia
PerformanceCounter cpuload = new PerformanceCounter();
cpuload.CategoryName = "Processor";
cpuload.CounterName = "% Processor Time";
cpuload.InstanceName = "_Total";
Console.WriteLine(cpuload.NextValue() + "%");
The output is always 0%, while the cpuload.RawValue
is like 736861484375 or so, what happened at NextValue()
?
输出始终为 0%,而cpuload.RawValue
类似于 736861484375 左右,发生了NextValue()
什么?
采纳答案by Nick Craver
The first iteration of he counter will always be 0, because it has nothing to compare to the last value. Try this:
计数器的第一次迭代将始终为 0,因为它与最后一个值没有任何比较。尝试这个:
var cpuload = new PerformanceCounter("Processor", "% Processor Time", "_Total");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Then you should see some data coming out. It's made to be seen in a constant graph or updated scenario...that's why you don't come across this problem often.
然后你应该会看到一些数据出来。它可以在恒定图形或更新的场景中看到……这就是您不经常遇到此问题的原因。
Here's the MSDN reference:
这是MSDN 参考:
The method nextValue() always returns a 0 value on the first call. So you have to call this method a second time.
方法 nextValue() 在第一次调用时总是返回 0 值。所以你必须第二次调用这个方法。
回答by Max
First retrieve first value (would be 0)
首先检索第一个值(将是 0)
NextValue();
Then wait for 1000 milisec
然后等待 1000 毫秒
Thread.Sleep(1000);
Then retrieve second value which is the true cpu usage.
然后检索第二个值,这是真正的 CPU 使用率。
NextValue();
The code should look like this:
代码应如下所示:
float perfCounterValue = perfCounter.NextValue();
//Thread has to sleep for at least 1 sec for accurate value.
System.Threading.Thread.Sleep(1000);
perfCounterValue = perfCounter.NextValue();
Console.WriteLine("Value: {0}", perfCounterValue);