cpulimit & taskset: control process CPU affinity & usage

cool_penguin_smallPlaying with processes on Linux is always fun. cpulimit and taskset are two cool and useful utilities to control the behaviour of your processes at a CPU-core level.

cpulimit

Lets you control or limit the CPU usage of a process. This will make a processor intensive process take longer to finish but will allow other processes to utilize the CPU. cpulimit works on both single or multi-core environments. Run the following command to install cpulimit on Ubuntu:

$ sudo apt-get install cpulimit

The easiest way to use cpulimit is to add cpulimit -l perecentage_of_cpu before your usual command. For example:

$ cpulimit -l 20 ghb

will run HandBrake (ghb) and force it to use around 20% of your processing capacity. cpulimit has options to attach to an already running process:

-p PID : attach to the process with PID process ID
$ cpulimit -l 20 -p 1234
 
-e prog_name : attach to theĀ  executable with name prog_name
$ cpulimit -l 20 -e ghb

The -b option runs cpulimit in the background.

taskset

taskset is a wrapper to the sched_setaffinity system call. Use it to control which processor core(s) a process can run on.

To start HandBrake on cores 0, 2 and 3:

$ taskset -c 0,2,3 ghb

To make a process with PID 1234 run on cores 0 and 2 (the output will show the current and changed affinity):

$ taskset -c -p 0,2 1234 //note: 0,2 comes after -p followed by PID
pid 1234's current affinity list: 0-3
pid 1234's new affinity list: 0,2

As you can see, before changing the affinity, the process could have run on any core from 0 to 3 (I have a quad core device). That’s the general affinity of any process started without taskset.

To know the current affinity of any process:

$ taskset -c -p PID

You can also use ps:

$ ps -o pid,psr,comm -p PID

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s