Black God

How to launch your application in a specific CPU in Linux (CPU affinity)?

CPU affinity is a characteristic of Scheduler, which assigns a specific set of CPUs to a Process. Once it is assigned, the Process scheduler can’t run this process in any other CPUs. Linux kernel does manage the CPUs effectively (Natural CPU affinity). This won’t result in dramatic change in performance of your system. In some database and server scenarios this is very useful. I am not sure about how to utilize this in a desktop system.

taskset utility – a part of utli-linux, which is installed by default in Ubuntu, does this job of assigning CPU affinity. This tool can set the CPU affinity for an existing process and also a new process launched. Let’s see how to use this utility.

This command defines CPU affinity in terms of Mask or CPU list. For example,

CPU 1 only => Mask: 0×00000001 => List: -c 1

CPU 1 & 2 => Mask: 0×00000003 => List: -c 1,2

The mask is of 32 bits each represents a CPU. The LSB is CPU1, LSB+1 is CPU2 and it goes on…

As per man page of taskset, the syntax is,

taskset [options] mask command [arg]…
taskset [options] -p [mask] pid
I just dive into basic examples without much blah blah stories.

How to launch an application with CPU affinity?

The below command will launch Google Chrome browser in CPU 1 & 2 (or 0 and 1). The mask is 0×00000003 and command is “google-chrome”.

taskset 0×00000003 google-chrome

How to know the CPU affinity of a running process?

The below command will return the CPU affinity of a Process with Process ID of 5808
$ taskset -p 5808
pid 5808′s current affinity mask: 3

How to change the CPU affinity of a running process?

The below command changes the CPU affinity of process 5808 from 3 to 1 (i.e., two CPUs to one CPU)

$ taskset -p 0×00000001 5808

pid 5808′s current affinity mask: 3

pid 5808′s new affinity mask: 1

You can refer man page of taskset for more details.

Leave a Reply

Your email address will not be published. Required fields are marked *