获取CPU和RAM使用率

编程入门 行业动态 更新时间:2024-10-28 02:34:30
本文介绍了获取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使用率

本文发布于:2023-11-16 16:49:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:使用率   CPU   RAM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!