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

C# C语言中的性能计数器不准确#,c#,performancecounter,C#,Performancecounter,我正在从事一个收集性能数据的项目,就像性能监视器一样 但是,当我以每秒页数运行监视器时,得到的结果与性能监视器不同。 我认为这是因为性能计数器没有给出所有的小数,平均值计算变得不准确 我的代码已更新: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Threading; using System.

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

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

我的代码已更新:

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();
        }
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用系统诊断;
使用系统线程;
Net系统;
使用制度管理;
使用System.Net.NetworkInformation;
命名空间性能监视器
{
班级计划
{
静态void Main(字符串[]参数)
{
List pagesSec=新列表();
PerformanceCounter memoryPages=新的PerformanceCounter(“内存”、“页数/秒”);
同时(计数<50)
{
pagesSecValue=memoryPages.NextValue();
pagesSec.Add(pagesSecValue);
Console.WriteLine(“页面:+pagesSecValue”);
计数++;
睡眠(1000);
Console.Clear();
}
Console.WriteLine(“平均页数/秒:+pagesSec.Average());
Console.ReadLine();
}
}
}
在运行程序时,大多数情况下我会在控制台上打印0

结果: 我的节目:406349 Windows性能监视器:12133


为什么会有差异?

您所做的计算与性能计数器不同。你要做的是每秒获取50秒的页面数,然后得到这50个数字的平均值。第一,显然性能计数器处理数据的时间更长。第二,这不是一个有用的平均值。性能计数器有效地获取了更高的样本。例如,如果“每秒页数”值在2秒内执行此操作,您认为会发生什么情况: 0 .5 1 1.5 2 5156204


你的代码在0秒,1秒和2秒取样?您的“平均值”为5,而性能计数器(如果在0.5秒采样,则不是)为10。

此计数器不准确的原因是您决定如何对其进行编码。如果你得到的是0,那么你做错了什么。请公布如何准确调用此循环。“由于你在提出这个问题之前缺乏研究,我不得不对这个问题投反对票。”拉姆霍恩,我发现你的前两句话荒谬地不言自明。显然有些地方出错了,当然这是OP如何编码的结果。否则他们就不会寻求帮助。我不明白这个问题说明了你缺乏研究,或者你缺少什么代码。谢谢你的回答。现在,我的采样率是每100ms一次,结果更接近Windows性能监视器的值。