c# - PerformanceCounter CPU 使用率值始终为 0

标签 c# performance

对于以下性能计数器,我总是得到 % Processor Time is 0,甚至我的 CPU 显示 100% 使用率,可能是什么原因?

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

最佳答案

NextValue() documentation 中的注释对此进行了解释:

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.

因此,如果您将代码更改为:

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

...然后您会看到适当的值。

关于c# - PerformanceCounter CPU 使用率值始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44280749/

相关文章:

c# - 线程池设计问题

javascript - HyperLink 上带参数的 Js 函数调用

python - 加载 txt 文件时跳过行

performance - 并发用户计算

c# - 在 C# 中使用泛型进行条件比较

c# - Nhibernate 和 MySQL 的 BLOB 索引前缀长度

c# - 使用带有存储过程的 Linq 是否比使用带有生成 SQL 的 Linq 执行得更好?

javascript - Javascript 中依赖于其范围之外的变量的函数会导致内存泄漏吗?

jquery - webpack结合多个版本的jquery来减少文件大小

javascript - javascript 中循环和 CPS 循环的完全奇怪的性能