PerformanceCounter(和 Performance Monitor)显示与任务管理器不同的结果

PerformanceCounter (and Performance Monitor) showing different result than Task Manager

我有以下代码:

PerformanceCounter c = new PerformanceCounter("Processor", "% Processor Time", "_Total");

然后我将它用于:c.NextValue()

我得到的 cpu 利用率大约是任务管理器管理器显示的两倍。虽然我的 cpu 有 2 个内核,但据我所知 that's not supposed to make a difference。那么为什么会这样呢?还是我对双核造成的错误? (虽然搜索了一段时间,但我找不到性能计数器列表的任何文档。)

编辑

正如评论中所建议的那样,我尝试了 perfmon(性能监视器),它显示的结果与我得到的相同。为什么会出现差异?

根据 this blog,如果您想匹配任务管理器的确切值,您应该使用 "Processor Information" 而不是 "Processor"。问题是什么值是正确的,但我想这是一个设计决定。

For someone performing performance testing and analysis, the ability to log CPU utilization data over time is critical. A data collector set can be configured via logman.exe to log the “% Processor Time”counter in the “Processor Information” object for this purpose.

PerformanceCounter c = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");

应该做。

如果你使用这个,你可以得到与任务管理器相同的结果:

 cpuCounter = new PerformanceCounter(
            "Processor Information",
            "% Processor Utility",
            "_Total",
            true
        );