Search code examples
perfmon

how to Get Average %User Time in Perfmon


I also understand I can also use this programatically by creating a performance counter by using System.Diagnostics.PerformanceCounter, and get the counter value using NextValue() method.

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) + " %");
                }

I found this code online and In Here I am more insterested in Calculating Average CPU and Average RAM at the end of this test and store it in a Var to compare it against another variable. any nice ideas

thanks


Solution

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