获取CPU和RAM使用率 [英] Get CPU and RAM usage

查看:190
本文介绍了获取CPU和RAM使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行过程期间,我需要获取ram内存和CPU使用率(该过程有时可能会运行30分钟以上)。与任务管理器的值相比,我可以获得免费的RAM,但CPU使用率不正确。难道我做错了什么?这是我的代码:

I need to get the ram memory and CPU usage during execution of a process (the process can run sometimes and over 30 minutes). I am able to get the free RAM but the CPU usage it's not correct, compared with the value from task manager. Am I doing something wrong? Here is my code:

class Program
{
    static List<float> AvailableCPU = new List<float>();
    static List<float> AvailableRAM = new List<float>();

    protected static PerformanceCounter cpuCounter;
    protected static PerformanceCounter ramCounter;
    static void Main(string[] args)
    {
        cpuCounter = new PerformanceCounter();
        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";

        ramCounter = new PerformanceCounter("Memory", "Available MBytes");

        try
        {
            System.Timers.Timer t = new System.Timers.Timer(1200);
            t.Elapsed += new ElapsedEventHandler(TimerElapsed);
            t.Start();
            Thread.Sleep(10000);
        }
        catch (Exception e)
        {
            Console.WriteLine("catched exception");
        }
        Console.ReadLine();

    }

    public static void TimerElapsed(object source, ElapsedEventArgs e)
    {
        float cpu = cpuCounter.NextValue();
        float ram = ramCounter.NextValue();
        Console.WriteLine(string.Format("CPU Value: {0}, ram value: {1}", cpu, ram));
        AvailableCPU.Add(cpu);
        AvailableRAM.Add(ram);
    }

}

但是当我运行程序时,与任务管理器中的值相比,这是打印到控制台的内容:

But when I run the program, here is what it's printed to the console, compared with values from task manager:

我在做什么错?

推荐答案

您的值没有问题。

原因您会看到与任务管理器返回的内容不同的是, CPU使用率值是在给定的时间间隔内计算的值,即两个 NextValue()之间的值电话。如果您同时执行任务管理器不调用其自己的NextValue(如果我们简化了它的工作方式),则不会返回相同的结果。

The reason you see differences with what task manager returns is that the "CPU usage" value is something computed for a given interval, i.e. between two NextValue() calls. If task manager "doesn't call its own NextValue" (if we simplify how it works) at the same time you do, you won't return the same results.

想象以下情形:

Time 0: 0% actual CPU usage
Time 1: 50% actual CPU usage
Time 2: 70% actual CPU usage
Time 3: 2% actual CPU usage
Time 4: 100% actual CPU usage




  • 如果检查时间1和时间3之间的值,您将返回基于 50%和2%的值。 / li>
  • 如果任务管理器检查了时间2和时间4之间的值,它将返回不同的值,即基于 70%和100%的值。

  • 您可以尝试生成自己的应用程序的多个进程,您还将看到不同的结果。

    You could try to spawn multiple processes of your own application, you should also see different results.

    这篇关于获取CPU和RAM使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆