How to use 100 percent CPU on all cores

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the bash category.

Last Updated: 2024-04-25

I wanted to see if monit would alert me when I used 100% CPU on my N-core server.

The first thing to do is to find out how many processors are available. This is possible using nproc. It returned the number 4.

Now to use up all the CPU cycles:

# go up to 8 if you have 8 cpus, etc.
# each of these will use a different core
for i in 1 2 3 4; do 
  # do the null operator and loop
  while : ; do
    : ;
  done &
done

After executing this code, all the loops will be running in the background. To see them, call jobs. To get their process ids: jobs -p. To stop them all: kill $(jobs -p)

Resources