是否有任何统一的方法来计算 PerformanceCounter 的任何类别中的任何计数器?

Is there any uniform method to calculate any counters within any category for PerformanceCounter?

我正在使用 C# 的 "PerformanceCounter" class 计算以下 2 个计数器 "Available Bytes" 和 "Memory" 类别下的“% Committed Bytes In Use”。

            PerformanceCounter pc = new PerformanceCounter("Memory", "Available Bytes", true);
        PerformanceCounter pc1 = new PerformanceCounter("Memory", "% Committed Bytes In Use", true);

        var a = pc.RawValue;
        var b = pc1.NextValue();

我在这里看到的问题是 "RawValue" 用于 "Available Bytes" 计数器,而 "NextValue()" 用于“% Committed Bytes In Use”计数器。

是否有任何统一的方法来计算两个或所有计数器?

根据我的经验和主要是 MSDN 文档,它因性能计数器类别而异,然后又因特定属性 属性 而异,例如 Available Bytes% Committed 在您的情况下。

您正在寻找的可能是 NextSample()。

Perf Counter

属性: RawValue

Gets or sets the raw, or uncalculated, value of this counter.

^ 这意味着它不一定取决于创建它的开发人员。

方法:NextValue()

Obtains a counter sample and returns the calculated value for it.

^ 意味着这取决于创建它的开发人员。

方法:NextSample()

Obtains a counter sample, and returns the raw, or uncalculated, value for it.

还有一些很久以前就向我解释过的东西,所以对它持保留态度,RawValue 的概念并不总是有效的。

RawValues 用于创建样本。 NextSample() 或样本 is/are 平均值 - 更真实 - 原始值随时间推移的平均值。 NextValue() 清理样本转换为 %,或从字节转换为千字节(基于值的上下文和开发人员的实现)。

因此,以我的愚见,即使信息已有 10 多年历史,也应放弃使用 RawValue 并在其位置使用 NextSample() - 如果您需要 realistic/accurate 值。

它只是因类别而异,因为不同的类别包含不同的计数器类型。 PerformanceCounter.CounterType property defines what type of data the counter is holding, and therefore how the data is calculated. It doesn't make sense for a counter that's measuring the difference over time to have the difference in the raw value because the difference could be over different time periods for different clients wanting to do the measurement. See the Performance Counter Type Enumeration for more info on the different types. If you really want to get into the details of how each type works, you have to resort to the Win32 documentation on which all of this is based. There used to be a single page with all of this, but I'm having trouble finding that at the moment. The closest I can find is here: https://technet.microsoft.com/en-us/library/cc960029.aspx。某些性能计数器类型使用一个主计数器和一个 "base" 计数器,然后使用基于每个计数器(可能还有系统时间)的当前和先前原始值的公式来计算 NextValue()RawValue 可能 看起来 对于某些计数器类型无效,因为以与计算值相同的方式解释它是没有意义的。例如,IIRC for % CPU used for the process,原始值是自程序启动以来使用的 CPU 滴答数,如果将其解释为百分比是无意义的。它仅在与之前的值和经过的时间(您还可以从中推断出最大可能的变化)进行比较时才有意义。

使用 RawValue 对某些计数器有意义,对其他计数器则不然。但是,NextValue() 通常不能在您第一次调用它时 return 一个有意义的值,因为当它被计算为样本之间的差异时,您没有之前的样本可以与之进行比较。您可以忽略它,或者您可以将代码设置为在启动期间调用一次,以便后续调用获得实际值。请记住,预计 NextValue() 将在计时器上调用。例如,如果您在 Network Bytes Sent 计数器上调用它,它将 return 上次调用与本次调用之间发送的字节数。因此,例如,如果您在初始调用后 2 秒调用 Network Bytes Sent 计数器上的 NextValue(),然后在 2 分钟后再次调用,您将获得非常不同的值,即使网络传输很稳定,因为调用2 秒后是 return 2 秒内传输的字节数,2 分钟后调用将 return 2 分钟内传输的字节数。

所以,简而言之,您可以对所有计数器类型使用 NextValue(),但您必须丢弃或忽略第一个值 returned,并且您必须调用 NextValue()结果有意义的固定间隔(就像交互式 Windows Performance Monitor 程序一样)。