Keep Reading

Limit your Linux's CPU Process

       I found cpulimit is  pretty useful for the scripts running from cron, for example I can do overnight backups and be sure that compression of 50GB file via rar won’t ate 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:
cd /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/rar archive.rar
You can check actual CPU usage by gzip using commands:
ps axu | grep rar
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 rar
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/cups -l 30