如何在Perfmon中获取平均%用户时间

时间:2012-11-08 17:29:59

标签: perfmon

我也理解我也可以通过使用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中,以便将其与另一个变量进行比较。任何好主意

感谢

1 个答案:

答案 0 :(得分: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();
        }
    }
}