How to limit CPU usage for individual processes in Ubuntu

You can limit the maximum CPU usage of a specific process in Ubuntu by using a tool called “cpulimit”.  This is useful for systems where you have an individual process causing strain on your systems resources and you need to free up some power for the rest of your systems processes to run properly and is especially useful in web hosting environments where you have terminal access and root or sudo credentials.

Before we begin, this tutorial assumes the following;

  1.  You are running an Ubuntu 16 or Ubuntu 18 operating system.
  2. You have root or sudo access.

1. Update apt-get and install cpulimit.

The first step is to update your apt-get repositories and install the cpulimit tool.

apt-get update && apt-get install cpulimit
sudo apt-get update && sudo apt-get install cpulimit

You can simulate a process that will take up most of your cpu using the dd command by using the following command.

dd if=/dev/zero of=/dev/null &

2. Find out the PID or name of the process you want to limit.

Use the top command to find out the PID (Process ID) or name of the process that you want to limit using the cpulimit tool.

Take note of the value in the PID or COMMAND column for the process that you want to limit using cpulimit.

3. Limit the cpu usage of the identified process.

You can now limit the cpu of the identified process in a couple of different ways. By using the PID or by using the process name/command.

To use the process/command, where -e is the process name/command, --limit is the maximum cpu usage before cpulimit kicks in, --cpu is the number of cpu assigned to your system. The --cpu value is optional as cpulimit can generally automatically detect this.  But if you experience issues where it’s not limiting the cpu usage correctly, kill the cpulimit process and run it again including the --cpu value. -b allows you to continue to use the command line after running the command.;

cpulimit -e dd --limit 50 --cpu 1 -b

cpu limited to 50% for the dd command
The process you limited will now be running no more than a few percent of the limit you set with the cpulimit command.

You call also limit using the pid by using the -p value instead of -e.

cpulimit -p 14421 --limit 50 --cpu 1 -b
To flag entire group of processes, you can flag the -P value, using the PID of any one of the processes running, for example  php-fpm processes or apache2, for example;

pidof php7.3-fpm
2442 3412 3110 3226

cpulimit -P 2442 --limit 50 --cpu 1 -b

IMPORTANT NOTE

If you intend on using this in a cronjob or a script, you should take note that each time you run the command spawns a new process.  If you dont want a million running cpulimit processes, be sure to kill off any that are not necessary.

Get paid to Google search

Be the first to comment

Leave a Reply

Your email address will not be published.


*