There can be cases when your server performance can slow down when even a single process uses all of your server CPU capability. Such usage will cause issues for other processes to work properly on your VPS instance. Since when one process is using all of the resources, other processes have to wain in the queue to start their tasks. This can be solved by limiting CPU resource usage with CPULimit software.
β
The main purpose of CPULimit is to set a restriction on the specific process on how much CPU it can use. When the limitation is implemented, there is no influence on the nice value or the settings on priorities, but on real CPU usage instead.
0. Requirements:
Root or sudo.
βnano or another text editor.
1.1 Installation if using Ubuntu/Debian:
sudo apt-get install cpulimit
1.2 Installation if using CentOS/Fedora:
Firstly, it will be required to install the EPEL repository if it was not done previously:
sudo yum install epel-release
Afterward, the installation can be initiated:
sudo yum install cpulimit
or
sudo dnf install cpulimit
2. Usage of CPULimit:
To check the effectiveness of CPULimit, let's create a process (usecpu.sh) that will consume all of your server's CPU:
sudo nano usecpu.sh
Enter the following code into the usecpu.sh file:
#!/bin/bash
while :; do :; done;
Save the code in your file. This code will create a loop that will consume all of the server's CPU. When the file is created, set executable permission for it:
sudo chmod +x usecpu.sh
The creation process can be started using:
./usecpu.sh &
After initiation, you will receive a result of the process id, for example, 1887:
[1] 1887
If everything is correct, the new process should use all of the server's CPU. You can check the usage of your CPU by using the top command:
As you can see from the table, the usecpu.sh process uses 99.9% of server CPU. Such CPU usage will prevent other processes from working successfully and can finally result in the server OS inactivity. This is where CPULimit comes to usage.
β
If you wish to limit the process to use only 30% of your server's total CPU, initiate the following command:
cpulimit -l 30 -p 2912 &
* -l 30 will set the limit to the provided number of %. In this case 30%.
* -p 2892 is used to identify the process by it's PID, as seen in the first column from top command.
Now, when the process is limited by CPULimit let's check the results again by initiating the top command:
Now the usecpu.sh process CPU consumption will be limited to 31.6% of CPU (can be +/- 5% deflection).
β
If you wish to use the process name instead of PID for the limitation, you can form your command from such an example:
cpulimit -l 25 ./usecpu.sh &