To emulate a CPU intensive task, we can use a tool called matho-prime which generates a list of prime numbers. If you ask it to generate a big enough list it will max out the CPU while it is working. To install matho-prime on Ubuntu or on a Raspberry Pi use: Let’s just start the task and see the CPU usage: This tells matho-primes to generate a list of primes from zero to nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine! The output is redirected to the file p.txt. The ampersand at the end tells the shell to run the program in the background meaning you are returned to the command prompt straight after starting the task. Now run the top command and notice the amount of CPU being used by the prime number generator.
Now let’s kill that task and look at how we can launch it at a lower priority. Exit top by pressing q, then type fg to bring matho-primes to the foreground and then press “Ctrl + C” to force the program to exit. Now start the program again but at the beginning of the command add the word nice: nice is a tool that tells Linux to schedule this task at a lower priority. The niceness ranges from -20 (most favorable scheduling) to 19 (least favorable). By default nice will schedule the task with a niceness of 10. By default normal tasks are started with a niceness of zero. This means that a task with a niceness of 10 will be seen as of a lower priority and will be given CPU resources less often. We can now start a second one of these prime number generator to emulate other tasks that you want to do on your machine (like web browsing or writing a document). This one will have a normal niceness as using the desktop should be a greater priority than running the prime number generator. Note that the output from this file is redirected to p2.txt. The output from top will look something like this:
As you can see, the process with the higher niceness receives less CPU time. This means that if you launch a CPU intensive task with nice, it won’t make your machine feel sluggish or cause it to respond slowly.
cpulimit
There is a another command called “cpulimit” which rather than changing the scheduling priority, it temporarily pauses a process to ensure that it doesn’t exceed the desired CPU usage. To install it type: Now run the CPU intensive prime number generator again and note its PID number using this command: The first column of the output is the PID. Now limit the CPU usage of that process like this: Where 16299 is the PID of the matho-primes process. A look with top will show something like this:
Going further
There is a companion command to nice called renice which will change the niceness of an existing process. Trying use top or ps with grep to get the PID of a process and use renice +19 16299 to set the priority to the lowest possible (where 16299 is the PID of the process). Feel free to add in the discussion in the comment below.