gpt4 book ai didi

c# - 为什么这个性能计数器总是返回零?

转载 作者:行者123 更新时间:2023-12-02 15:20:43 25 4
gpt4 key购买 nike

我有这个代码:

using (PerformanceCounter pfc = new PerformanceCounter("Processor", "% Processor Time", "_Total"))    
return pfc.NextValue();

即使总 CPU 使用率不为零,此始终返回 0,并且在性能监视器中查看时相应的计数器也不为 0。

为什么?我需要做什么才能简单地返回总 CPU 使用率?

这是一个 Windows 8.1 虚拟机。

最佳答案

来自MSDN :

If the calculated value of a counter depends on two counter reads, the first read operation returns 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. The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read.

因此,我想说“%处理器时间”计数器的计算值取决于两个计数器读数,因此根据文档,您看到的第一个是 0.0。

我使用他们在读取之间等待一秒钟的建议对其进行了测试。每次第一次读取时我都会得到 0.0,但之后就会得到正值。

using (PerformanceCounter pfc = new PerformanceCounter("Processor", "% Processor Time", "_Total"))
{
MessageBox.Show(pfc.NextValue().ToString());
Thread.Sleep(1000);
MessageBox.Show(pfc.NextValue().ToString());
Thread.Sleep(1000);
MessageBox.Show(pfc.NextValue().ToString());
}

关于c# - 为什么这个性能计数器总是返回零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21420207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com