How to limit CPU processes in percentage on Linux

What is cpulimit

Cpulimit —  is a tool that limits the CPU usage of a process (expressed as a percentage, not CPU time). It’s useful to control different software when you don’t want them to consume too much % of CPU. The goal is to prevent the process from running longer than the specified time. This does not change the value or other scheduling priority settings, but it does change the actual CPU usage. In addition, it is able to dynamically and quickly adapt to the overall system load. CPU usage is controlled by sending SIGSTOP and SIGCONT POSIX signals to processes. All child processes and threads of the specified process will share the same percentage of the CPU.

How to install cpulimit

First, we login to our server and execute the command:

Ubuntu/Debian: apt install cpulimit
CentOS/RHEL: yum install cpulimit

We limit the CPU usage with the –limit or -l command to set the usage percentage for the process. Before limiting CPU usage, we need to find the process that is “eating” all the CPU time.

We run the “top” and see which process is doing the biggest load on the CPU.
Next, we look at what PID it has and run a command to limit the CPU usage of this process (where process_pid is indicated, we indicate the PID of our process, and where CPU is indicated, we indicate percentages)

cpulimit -p process_pid -l 20

We see that “cpulimit” saw that such a process exists, then we open another connection to the server and watch the load again using the “top”.

As you can see, the process really now uses not all 100% of the CPU, but 23% (a little more than we indicated).

In order for “cpulimit” to continue limiting the process to the background when we disconnect from the server, we add -background or -b value to the command so that the command looks like this:

cpulimit -p process_pid -l 20 -b

After executing this command, you can safely close the terminal and not worry that any service you have limited will again make a large load on the CPU.