1

I have a task to get a piece of c# code to make my CPU go 100% consistently. I have tried infinite loops, big integer calculations, concatenation of numerous very long strings.... everything either goes to 100% for a few moments and then down to like 60% or doesn't go to 100% at all.

Is there a simple piece of code that can achieve this?

Also using Windows 10

Decorayah
  • 75
  • 1
  • 8
  • Are you using threads? If not, then on the CPU in the number of cores more than one you will not be able to load 100%. – Vasek Mar 09 '18 at 23:52
  • "_I have a task to get a piece of c# code to make my CPU go 100% consistently._" Why? Just use something like Prime95 if you want to get close to 100% CPU load. –  Mar 09 '18 at 23:55
  • Useful to me. I'm using this artificial load for "poor man's fan control". My laptop cycles the fans on and off, and they make an annoying sound when they turn on, so I'd prefer that they just stay on all of the time. I am able to read the fan speed, but there is no interface to actually control the fans directly. So, I wrote a program to read the fan speed and generate some low-priority artificial load if they get "too slow" (about to turn off) to nudge them up a bit. The "while(true)" loop mentioned below does the trick. – Truisms Hounds Aug 02 '22 at 15:04

2 Answers2

6

You would want to implement threading for this as was previously stated. Your thread would call a method that contains a while(true) loop. For example:

Random rand = new Random()
List<Thread> threads = new List<Thread>();

public void KillCore()
{
     long num = 0;
     while(true)
     {
          num += rand.Next(100, 1000);
          if (num > 1000000) { num = 0; }
     }
}

public void Main()
{
     while (true)
     {
          threads.Add( new Thread( new ThreadStart(KillCore) ) );
     }
}

You don't have to add the threads to a list but you may want to if you somewhere down the road want to call Thread.Abort() to kill them off. To do this you would need a collection of some sort to iterate through and call the Abort() method for every Thread instance in the collection. The method to do that would look as follows.

public void StopThreads()
{
     foreach (Thread t in threads) { t.Abort(); }
}
  • 2
    `while(true);` is enough to consume 100% of a single core. `Random` there is completely unnecessary and `Random` is not thread-safe. – n0rd Mar 10 '18 at 00:38
1

use parallel for to maximize the CPU Cores usage and get the best of threading , inside each thread create an infinite loop using while(true) and congratulations you have **** your CPU :D