为什么 cpu 性能计数器一直报告 0% cpu 使用率?

发布于 2024-08-20 02:46:23 字数 337 浏览 3 评论 0原文

PerformanceCounter cpuload = new PerformanceCounter();
cpuload.CategoryName = "Processor";
cpuload.CounterName = "% Processor Time";
cpuload.InstanceName = "_Total";
Console.WriteLine(cpuload.NextValue() + "%");

输出始终为 0%,而 cpuload.RawValue 类似于 736861484375 左右,NextValue() 发生了什么?

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()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏の忆 2024-08-27 02:46:24

计数器的第一次迭代将始终为 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() + "%");

然后你应该看到一些数据出来。它是为了在恒定的图表或更新的场景中看到的......这就是为什么你不会经常遇到这个问题。

以下是 MSDN 参考

方法 nextValue() 总是返回
第一次调用时值为 0。所以你
必须再次调用此方法
时间。

The first iteration of the counter will always be 0, because it has nothing to compare to the last value. Try this:

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:

The method nextValue() always returns
a 0 value on the first call. So you
have to call this method a second
time.

牵你的手,一向走下去 2024-08-27 02:46:24

首先检索第一个值(将为 0)

NextValue();

,然后等待 1000 毫秒,

Thread.Sleep(1000);

然后检索第二个值,即真实的 cpu 使用情况。

NextValue();

代码应该如下所示:

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);

First retrieve first value (would be 0)

NextValue();

Then wait for 1000 milisec

Thread.Sleep(1000);

Then retrieve second value which is the true cpu usage.

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文