Linux Programming

How to limit CPU usage of process

There are often times when you come across programs that eat up your system resources unnecessarily. There can be many reasons why a program is behaving in such a manner. Maybe a package that you installed is buggy or its default behavior is set this way. In such scenario your system may become unstable and crash. So in the article we are going to talk about a simple program called cputlimit which will allow you to allocate CPU usage to such processes. cpulimit is small yet very powerful piece of program which binds your process to certain usage level.

If you don’t have already installed cpulimit on your system. You can download and install it from the following commands.

Debian based systems:

sudo apt-get install cpulimit

RedHat based system:

sudo yum install cpulimit

Arch based systems:

pacman -Syy cpulimit

On any other Linux distro you can just grab the source code and compile it yourself. You can fetch the source code from github.

After cpulimit is set up, all you need to figure out is how much of a CPU usage you want to allocate to certain process.

limit CPU usage of process

After you have installed cpulimit on your system,  you can set it to limit CPU usage for desired process, e.g. the command below executes gzip compression so that gzip process will never step over 10% of CPU limit:

#cpulimit --limit=10 /bin/gzip file-name.tar

You can check actual CPU usage of gzip using following commands:

#ps axu | grep [g]zip

or

#top

btw, the first command contains ‘grep [g]zip’ to avoid the last line in common output.

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:

#cpulimit -p 2342 -l 20

It’s also possible to specify process by its executable file instead of PID:

#cpulimit -P /usr/sbin/nginx -l 30

 

About the author

Ajay Verma

A Computer Science Graduate, who works extensively on open source projects. His Areas Of interest are: Network Security, Linux Administration, FOSS, Python, and C programming.

Add Comment

Click here to post a comment