How to Increase CPU Usage

By | June 25, 2019

The title of this post looks ridiculous, usually high CPU usage is a problem that slows down your computer and people are fighting to reduce CPU usage. However in my particular case I was working on CPU monitoring code and I need some tool that makes CPU consumption higher. So I created simple C# console application that my increase CPU load and also read back CPU percentage using Win32_Processor WMI class and I want to share it with you. The idea is simple to create multiple thread with while loop, number of threads is specified as program argument. More threads – higher CPU consumption:

High CPU usage application


Here is the code:


using System;
using System.Threading;
using System.Diagnostics;
using System.Management;
namespace HighCPUUsage
{
   class Program
   {
      static void Main(string[] args)
      {
         Debugger.NotifyOfCrossThreadDependency(); // for debugging
         int threadCount = Environment.ProcessorCount;
         Console.WriteLine(“High CPU Usage application. Press ctrl/c for interrupt!”);
         if (args.Length>= 1)
         {
            threadCount = Int32.Parse(args[0]);
         }
         for (int ii = 0; ii < threadCount; ii++)
          {
            Thread thread1 = new Thread(new ThreadStart(ThreadFunction));
            thread1.Start();
         }
         Console.WriteLine(“Number of threads: {0}”, threadCount);
         SelectQuery cpuQuery = new SelectQuery(“SELECT LoadPercentage FROM Win32_Processor”);
         Console.Write(“Cpu usage: “);
         int x = Console.CursorLeft;
         int y = Console.CursorTop;
         while (true)
         {
            ManagementObjectSearcher mgmtObjSrchr = new ManagementObjectSearcher(cpuQuery);
            foreach (ManagementObject cpuLoad in mgmtObjSrchr.Get())
            {
               string cpuPercent = cpuLoad.GetPropertyValue(“LoadPercentage”).ToString();
               Console.CursorLeft = x;
               Console.CursorTop = y;
               Console.Write(“{0}%”, cpuPercent);
            }
            Thread.Sleep(1000);
         
      }
      static void ThreadFunction()
      {
         while (true)
         {
         }
      }
   }
}

Here is the comparison with WMI query using wmic tool:
High CPU usage application
By the way Task Manager shows a bit high percentage.

Leave a Reply

Your email address will not be published. Required fields are marked *