Click here to Skip to main content
Click here to Skip to main content

CPU Usage with graphical indication using C# .NET

By , 19 Nov 2012
 

Introduction 

This article describes how to measure CPU usage using C#. For this example I have used a set of defined based classes provided by http://www.mentalis.org. You can download the supporting class from http://www.mentalis.org/soft/class.qpx?id=12. Moreover in this example it will use these base classes to get the CPU usage values and then it’s represented in a graphical format using the .NET Chart control. This will work fine with Windows (PlatformID.Win32NT, PlatformID.Win32Windows).  

Background 

Sometimes there are requirements to dynamically adjust performance settings in server applications and in order to do that we might need to calculate the CPU usage. Basically what we do in this code is calculate the CPU usage value and represent it in a graphical format. The calculations are performed by a separate thread. It’s advised not to use System.Windows.Forms.Timer but we can use System.Threading.Timer for more accurate results.

Using the code 

Importing libraries

using System.Windows.Forms.DataVisualization.Charting;
using Org.Mentalis.Utilities;
using System.Threading;

First initialize the chart settings:

bool iscontinue = true;
private static CpuUsage cpu;

private void Form1_Load(object sender, EventArgs e)
{
    //Chart Settings 
    // Populating the data arrays.
    this.cpuUsageChart.Series.Clear();
    this.cpuUsageChart.Palette = ChartColorPalette.SeaGreen;
     
    // Set chart title.
    this.cpuUsageChart.Titles.Add("CPU Usage");

    // Add chart series
     Series series = this.cpuUsageChart.Series.Add("CPU Usage");
     cpuUsageChart.Series[0].ChartType = SeriesChartType.FastLine;

     // Add Initial Point as Zero.
    series.Points.Add(0);

    //Populating X Y Axis  Information 
    cpuUsageChart.Series[0].YAxisType = AxisType.Primary;
    cpuUsageChart.Series[0].YValueType = ChartValueType.Int32;
    cpuUsageChart.Series[0].IsXValueIndexed = false;

    cpuUsageChart.ResetAutoValues();
    cpuUsageChart.ChartAreas[0].AxisY.Maximum =100;//Max Y 
    cpuUsageChart.ChartAreas[0].AxisY.Minimum = 0;
    cpuUsageChart.ChartAreas[0].AxisX.Enabled = AxisEnabled.False;
    cpuUsageChart.ChartAreas[0].AxisY.Title = "CPU usage %";
    cpuUsageChart.ChartAreas[0].AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount;

    populateCPUInfo();     
}

Next populate CPU information:

// Creates and returns a CpuUsage instance that
// can be used to query the CPU time on this operating system.
cpu = CpuUsage.Create();

int process = cpu.Query(); //Determines the current average CPU load.

private void populateCPUInfo()
{
    try
    {
        // Creates and returns a CpuUsage instance that can be
        // used to query the CPU time on this operating system.
        cpu = CpuUsage.Create();
 
        /// Creating a New Thread 
        Thread thread = new Thread(new ThreadStart(delegate()
        {
            try
            {
                while (iscontinue)
                {
                    //To Update The UI Thread we have to Invoke  it. 
                    this.Invoke(new System.Windows.Forms.MethodInvoker(delegate()
                    {
                        int process = cpu.Query(); //Determines the current average CPU load.
                        proVal.Text = process.ToString() + "%";
                        cpuUsageChart.Series[0].Points.AddY(process);//Add process to chart 

                        if (cpuUsageChart.Series[0].Points.Count > 40)
                        //clear old data point after Thrad Sleep time * 40
                            cpuUsageChart.Series[0].Points.RemoveAt(0);

                    }));

                    Thread.Sleep(450);//Thread sleep for 450 milliseconds 
                }
            }
            catch (Exception ex)
            {

            }

        }));

        thread.Priority = ThreadPriority.Highest;
        thread.IsBackground = true;
        thread.Start();//Start the Thread
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

We are using 450 milliseconds as interval.

Points of interest

This will only work in a Windows environment. Since CPU usage is a very rapid process, the values shown in your Operating System and the sample application might not tally all the time since updating the UI would consume time.

License

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

About the Author

Tyronne Thomas
Software Developer (Senior)
Sri Lanka Sri Lanka
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionThanksmemberFishCommander20 Nov '12 - 13:36 
Questionsimilar thingmemberfdkjhfds21 Aug '12 - 6:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 19 Nov 2012
Article Copyright 2012 by Tyronne Thomas
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid