2012-11-08 53 views
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比较它与另一个变量的更多insterested。任何好的想法

感谢

回答

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(); 
     } 
    } 
}