June 4, 2012

How to simulate high CPU load on Unix

Sometimes you want to stress a server by simulating high CPU load. Friend of mine tried to write a Fibonacci sequencer, but there is a better way. GNU Coreutils contains relatively unknown "yes" program.
yes prints the command line arguments, separated by spaces and followed by a newline, forever until it is killed. If no arguments are given, it prints ‘y’ followed by a newline forever until killed.
This gives us exactly what we want, an endless loop to occupy the processor. If you have only one processor core. Following is sufficient:


$ yes > /dev/null


Redirecting to /dev/null is important because we don't want to spend time waiting on IO. We want processor looping a fast as possible.
In case you have more than one processor core, which most of the modern CPUs do. Running one instance is not enough. To load all the cores, at least an equivalent amount of instances is required. How many cores you computer has? If you on linux, grepping /proc/cpuinfo will give you that information.


$ grep processor /proc/cpuinfo | wc -l
4


Combining what we know now. It is trivial to write a one-liner to max out all cores on the machine.


$ CN=`grep processor /proc/cpuinfo | wc -l`; \
  for i in `seq 1 $CN`; do \
  yes >/dev/null & \
  done


To stop the load if those are the only jobs you're running
$ kill `jobs -p`


or
$ killall yes

No comments: