How to limit the CPU usage of a Linux process

Last updated on September 4, 2020 by Dan Nanni

If you are a Linux system admin, there are cases where you would like to limit the CPU usage of a certain process such that the process does not eat up more than X% of CPU resource at any time. cpulimit is a command-line Linux program that can do exactly that, i.e., limiting the CPU usage of a Linux process in percentage. It monitors the CPU usage of a specified process as a daemon, and adjusts its CPU utilization dynamically.

Install cpulimit on Linux

To install cpulimit on Ubuntu or Debian:

$ sudo apt-get install cpulimit

To install cpulimit on Fedora:

$ sudo yum install cpulimit

To install cpulimit on CentOS or RHEL, first enable EPEL repository on your system, and then run:

$ sudo yum install cpulimit

Limit CPU Usage of a Process with cpulimit

Example usages of cpulimit are shown below:

$ sudo cpulimit -p 8645 -l 10
$ sudo cpulimit -e /usr/local/bin/myprog -l 20

The first command monitors the CPU usage of a process with PID 8645, and limits its CPU usage to 10%. Similarly, the second command limits the CPU usage of /usr/local/bin/myprog to 20%.

The cpulimit program runs as a user-space daemon which sends SIGSTOP and SIGCONT signals to a specified Linux process to adjust its CPU usage dynamically. Note that cpulimit must be executed either by the root or by the owner of the process being monitored. Conceptually, cpulimit works as follows.

while (1) {
     wait for some time
     send SIGSTOP to the process
     wait for some time
     send SIGCONT to the process
}

Testing with Debian indicates that cpulimit is not SMP-aware. That is, specifying -l X actually means X% of one CPU. So for example, if you set -l 100 on a dual-core machine, you are limiting the usage to 50% of available CPU resource.

Note that cpulimit does not work with some specific kernel processes such as kcryptd or kworker, which just ignore SIGSTOP signal.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean