c# -性能计数器低于Taskmanager %

本文关键字:Taskmanager 性能计数器 | 更新日期: 2023-09-27 18:06:45

我尝试做一个类,将从pc获取不同的用法,我有atm的问题是,CPU使用率是在任务管理器显示(约10%)。

请您看一下,给我指个正确的方向好吗?请不要不加解释的回答,我想学习!

下面是我手头的资料:

using System.Diagnostics;
using System.Net.NetworkInformation;
namespace ConsoleApplication2
{
    class UsageFetcher
    {
        ulong totalRAM;
        PerformanceCounter cpuUsage;
        PerformanceCounter ramUsage;
        PerformanceCounter diskUsage;
        NetworkInterface[] networkUsage;
        public UsageFetcher()
        {
            // Fetching total amount of RAM to be able to determine used persantage
            //totalRAM = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
            totalRAM = this.getTotalRam();
             // Creating a new Perfromance Counter who will be used to get the CPU Usage
            cpuUsage = new PerformanceCounter();
            // Setting it up to fetch CPU Usage 
            cpuUsage.CategoryName = "Processor";
            cpuUsage.CounterName = "% Processor Time";
            cpuUsage.InstanceName = "_Total";
            /*
             * Fetching the first two reads
             * First read is always 0 so we must elimiate it
             */
            cpuUsage.NextValue();
            cpuUsage.NextValue();
            // Creating a new Performance Counter who will be used to get the Memory Usage
            ramUsage = new PerformanceCounter();
            // Setting it up to fetch Memory Usage
            ramUsage.CategoryName = "Memory";
            ramUsage.CounterName = "Available Bytes";
            // Fetching the first two reads !! Same reason as above !!
            ramUsage.NextValue();
            ramUsage.NextValue();
        }
        public string getCPUUsage()
        {
            /* 
             * Requesting the usage of the CPU
             * It is returned as a float thus I need to call ToString()
             */
            return cpuUsage.NextValue().ToString();
        }
        public string getMemUsage()
        {
            // Requesting memory usage and calculate how much is free
            return (100 -ramUsage.NextValue() / totalRAM * 100).ToString();
        }
        public ulong getTotalRam()
        {
            return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory ;
        }
    }
}

c# -性能计数器低于Taskmanager %

根据这个帖子:为什么cpu性能计数器一直报告0%的cpu使用率?

你需要睡眠至少一秒钟的NextValue()方法返回一个像样的结果。

尝试在调用NextValue之间添加一个Sleep调用,看看会得到什么