Click here to Skip to main content
15,877,103 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please help...

I am trying to get an average CPU usage reading over a 5 second time-slice using code I have cobbled together from multiple forums but I am struggling...

Code so far
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.Timers;
using System.Threading;

namespace ConsoleApplication6
    class Program
        static void Main(string[] args)
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 2000;
            aTimer.Enabled = true;
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
               PerformanceCounter CPU = new PerformanceCounter("Processor", "% Processor Time", "_Total"); 
// I would like to get 5 samples of CPU and then calculate an average e.g. CPUTotal = (CPU1 + CPU2 + CPU3 + CPU4 + CPU5) / 5
//   console.writeline(CPUTotal + "%");

Any help please?

Play around with something like this.
If you insist on using a timer, store the result of your perf-counter somewhere and calculate it later.

static void Main( string[] args )
    PerformanceCounter perfCounter = new PerformanceCounter( "Processor", "% Processor Time", "_Total" );
    float sum = 0;
    int rounds = 0;
    while ( rounds < 5 )
        sum += perfCounter.NextValue();
        Thread.Sleep( 1000 );


    Console.Out.WriteLine( sum / rounds );
    Console.Out.WriteLine( "Done" );
Share this answer
Share this answer

The timer is there so that it can collect a number of metrics every x minutes eg. every 10 minutes get the average CPU usage of 5 samples, get the available RAM etc. etc.

So, if I understand correctly, sum/rounds = the average CPU usage over the rounds?
e.g. Round 1 cpu usage = 0% (it always is on the first sample), Round 2 cpu usage = 5%, Round 3 cpu usage = 7%. Total over 3 rounds = 12%, divide by 3 rounds = 4% average usage?

Also, how do I get the "sampling" to close as it keeps going after 3 rounds?
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900