Limiting CPU Usage with CPULimit
Server performance can degrade when a single process consumes all CPU resources, causing other processes to queue and wait, leading to potential performance issues on your VPS instance. This problem can be addressed by limiting CPU resource usage with CPULimit software.
CPULimit's primary function is to restrict the CPU usage of a specific process. This restriction affects actual CPU usage without altering the process's nice value or priority settings.
Requirements
- Root or sudo access
nano
or another text editor
Step 1: Installation
On Ubuntu/Debian
sudo apt-get install cpulimit
On CentOS/Fedora
First, install the EPEL repository if it is not already installed:
sudo yum install epel-release
Then, install CPULimit:
sudo yum install epel-release
Afterward, the installation can be initiated:
sudo yum install cpulimit
or
sudo dnf install cpulimit
Step 2: Create a High-CPU Usage Process
To demonstrate the effectiveness of CPULimit, create a script that consumes all CPU resources:
- Create the
usecpu.sh
file:
- Enter the following code into the file:
#!/bin/bash
while :; do :; done;
- Save the file and make it executable:
- Start the process:
Note the process ID (PID) that is displayed (e.g., 1887).
Verify the CPU usage with the top
command:
As shown in the table, the usecpu.sh
process is consuming 99.9% of the server's CPU. This high CPU usage can hinder other processes and potentially lead to server OS inactivity. CPULimit can help manage this by limiting CPU usage for specific processes.
To limit the usecpu.sh
process to 30% of your server's total CPU, use the following command:
cpulimit -l 30 -p 2912 &
-l 30
sets the CPU usage limit to 30%.
-p 2912
specifies the process ID (PID), as seen in the first column of the top
command output.
Now, with the process limited by CPULimit, check the results again by running the top
command:
top
This will show the updated CPU usage, reflecting the limit set by CPULimit.
Step 3: Limit CPU Usage with CPULimit
To limit the CPU usage of the usecpu.sh
process to 30%, use the following command:
cpulimit -l 30 -p 1887 &
-l 30
sets the CPU limit to 30%.
-p 1887
specifies the process ID.
Check the CPU usage again with top
to see the limited usage:
top
Now the usecpu.sh process CPU consumption will be limited to 31.6% of CPU (can be +/- 5% deflection).
If you wish to use process name instead of PID for the limitation, you can form your command from such example:
cpulimit -l 25 ./usecpu.sh &
Conclusion
Using CPULimit allows you to manage CPU usage effectively, ensuring that no single process can monopolize server resources. This helps maintain overall server performance and prevents potential issues caused by high CPU consumption.