I recently wanted to get the usage of my CPU in C#. After searching the internet I found a way of doing it using the PerfomanceCounter class. I made a couple of changes and I created the following class, which seems to work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;</code>

{
   public class SystemUtils
   {
      public static long getCpuUsage()
      {
        PerformanceCounter cpuCounter;
        cpuCounter = new PerformanceCounter();

        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";

        cpuCounter.NextValue();
        System.Threading.Thread.Sleep(1000);
        return (int) cpuCounter.NextValue();
      }
    }
}

Using the statement: SystemUtils.getCpuUsage() you should be able to get an integer number showing the CPU usage.

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required

Page last modified: 05:48 on November 6, 2013 (UTC+2)