cpulimit is a small program written in C that allows to limit CPU usage by Linux process. Limit is specified in percentage so it’s possible to prevent high CPU load generated by scripts, programs or processes.
cpulimit is pretty useful for the scripts running from cron, for example you can do overnight backups and be sure that compression of 50GB file via gzip won’t eat all CPU resources and all other system processes will have enough CPU time.
In most of Linux distributions cpulimit is available from binary repositories so you can install it using commands:
sudo apt-get install cpulimit
or
sudo yum install cpulimit
If it’s not possible in your distro then it’s extremely easy to compile it:
scd /usr/src/ wget --no-check-certificate https://github.com/opsengine/cpulimit/tarball/master -O cpulimit.tar tar -xvf cpulimit.tar cd opsengine-cpulimit-9df7758 make ln -s cpulimit /usr/sbin/cpulimit
From that moment you can run commands limited by CPU percentage, e.g. below command executes gzip compression so that gzip process will never step over 10% of CPU limit:
/usr/sbin/cpulimit –limit=10 /bin/gzip vzdump-openvz-102-2012_06_26-19_01_11.tar
You can check actual CPU usage by gzip using commands:
ps axu | grep [g]zip
or
top
Btw, the first command contains ‘grep [g]zip’ to avoid the last line in common output:
root 896448 10.0 3.1 159524 3528 ? S 13:12 0:00 /usr/sbin/cpulimit --limit=10 /bin/gzip vzdump-openvz-102-2012_06_26-19_01_11.tar root 26490 0.0 0.0 6364 708 pts/0 S+ 15:24 0:00 grep gzip
Using cpulimit you can also allocate CPU limit to already running processes, e.g. below command will allocate 20% CPU limit to process with PID 2342:
/usr/sbin/cpulimit -p 2342 -l 20
It’s possible to specify process by its executable file instead of PID:
/usr/sbin/cpulimit -P /usr/sbin/nginx -l 30