C#中的性能计数器不准确

时间:2012-09-04 11:34:04

标签: c# performancecounter

我正在开发一个收集性能数据的项目,就像性能监视器一样。

但是,当我以页/秒运行监视器时,它会提供与性能监视器不同的结果。 我认为这是因为性能计数器没有给出所有小数,并且平均计算变得不准确。

我的代码更新:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Management;
using System.Net.NetworkInformation;

namespace PerformanceMonitor
{
    class Program
    {

        static void Main(string[] args)
        {
       List<float> pagesSec = new List<float>();
        PerformanceCounter memoryPages = new PerformanceCounter("Memory", "Pages/sec");

        while (count < 50)
        {
            pagesSecValue = memoryPages.NextValue();
            pagesSec.Add(pagesSecValue);


           Console.WriteLine("Pages: " + pagesSecValue);
           count++;

            Thread.Sleep(1000);
            Console.Clear();
        }

Console.WriteLine("Avg pages/sec: " + pagesSec.Average());

 Console.ReadLine();
        }
}
}

在运行程序时,大多数时候我在控制台上打印0。

结果: 我的节目:4,06349 Windows性能监视器:12,133

为什么会有差异?

1 个答案:

答案 0 :(得分:2)

您正在执行与性能计数器不同的计算。你正在做的是每秒获取一次页数,每秒50秒,得到这50个数字的平均值。其一,显然性能计数器正在使用更长时间的数据。二,这不是一个有用的平均值。性能计数器实际上采用了更高的样本。例如,如果每秒页数值在2秒内完成此操作,您认为会发生什么: 0 .5 1 1.5 2 5 15 6 20 4

你的代码在0,1和2秒采样?你的“平均值”是5,而性能计数器(如果它以.5秒采样,它没有采样)将是10。