CPU affinity an overview

When you are using SMP (Symmetric MultiProcessing) you might want to override the kernel’s process scheduling and bind a certain process to a specific CPU(s).

But what is CPU affinity?

CPU affinity is nothing but a scheduler property that “bonds” a process to a given set of CPUs on the SMP system. The Linux scheduler will honor the given CPU affinity and the process will not run on any other CPUs. Note that the Linux scheduler also supports natural CPU affinity:

The scheduler attempts to keep processes on the same CPU as long as practical for performance reasons. Therefore, forcing a specific CPU affinity is useful only in certain applications. For example, the application such as Oracle (ERP apps) use # of CPUs per instance licensed. You can bound Oracle to specific CPU to avoid license problem. This is a really useful on large server having 4 or 8 CPUS

Setting processor affinity for a certain task or process using “taskset” command:

The command taskset is used to set or retrieve the CPU affinity of a running process given its PID or to launch a new COMMAND with a given CPU affinity. However taskset is not installed by default. You need to install schedutils (Linux scheduler utilities) package.

Install schedutils

Debian Linux:
# apt-get install schedutils

Red Hat Enterprise Linux:
# up2date schedutils
OR
# rpm –ivh schedutils*

Under latest version of Debian / Ubuntu Linux/RHEL etc taskset is installed by default using util-linux package.

# apt-get install util-linux

# yum install util-linux

The CPU affinity is represented as a bitmask, with the lowest order bit corresponding to the first logical CPU and the highest order bit corresponding to the last logical CPU. For example:

0x00000001 is processor #0 (1st processor)
0x00000003 is processors #0 and #1
0x00000004 is processors #2 (3rd processor)

To set the processor affinity of process 13545 to processor #0 (1st processor) type following command:

# taskset 0x00000001 -p 13545

If you find a bitmask hard to use, then you can specify a numerical list of processors instead of a bitmask using -c flag:
# taskset -c 1 -p 13545
# taskset -c 3,4 -p 13545

Where,

-p : Opera

ps -eo psr,pid

this gives the processor in each the pid is current assigned to.

taskset -p option pid
option 1 means 1st processor
option 2 means 2nd processor
option 0xffffffff means all the processor