0

我也知道我也可以通过使用创建性能计数器以编程方式使用它System.Diagnostics.PerformanceCounter,并使用 NextValue() 方法获取计数器值。

Process p = Process.GetProcessById(10204);
            PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set - Private", p.ProcessName);
            PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% User Time", p.ProcessName);
                while (true)
                {
                    Thread.Sleep(1000);
                    double ram = ramCounter.NextValue();
                    double cpu = cpuCounter.NextValue();
                    Console.WriteLine("RAM: " + (ram / 1024 / 1024) + "MB");
                    Console.WriteLine("CPU: " + (cpu) + " %");
                }

我在网上找到了这段代码,在这里我更感兴趣的是在这个测试结束时计算平均 CPU 和平均 RAM,并将其存储在 Var 中以将其与另一个变量进行比较。任何好主意

谢谢

4

1 回答 1

0
using System;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            double totalRam = 0.0d;
            double cpu = 0.0d;

            Process p = Process.GetProcessById(1188);
            var ramCounter = new PerformanceCounter("Process", "Working Set - Private", p.ProcessName);
            var cpuCounter = new PerformanceCounter("Process", "% User Time", p.ProcessName);
            int n = 0;
            while (n < 20)
            {
                Thread.Sleep(1000);
                double ram = ramCounter.NextValue();
                cpu += cpuCounter.NextValue();
                totalRam += (ram / 1024 / 1024);
                n++;
            }

            double avgRam = totalRam/n;
            double avgCpu = cpu/n;
            Console.WriteLine("Average Ram is {0} ", avgRam);
            Console.WriteLine("Average Cpu is {0} ", avgCpu);
            Console.ReadLine();
        }
    }
}
于 2012-11-09T10:13:50.243 回答