Disclaimer: This recipe is focused on SMP computers only.
Description: CPU affinity is a scheduler property that binds a process to a given set of CPUs on the system, so that the system scheduler won’t run this process on any other CPUs. By default, the scheduler tries to keep processes on the same CPU as long as it makes sense for performance reasons, so forcing CPU affinity is useful only in some cases (per processor licensing, testing, broken hardware, etc).
CPU affinity is represented as a bitmask (given in hexadecimal), with the lowest order bit corresponding to the first logical CPU and the highest order bit corresponding to the last logical CPU. Examples:
- CPU #0: 0×00000001
- CPU #1: 0×00000002
- CPU #2: 0×00000004
- CPU #3: 0×00000008
- CPU #0 and CPU #1: 0×00000003
- CPU #2 and CPU #3: 0x0000000C
- All CPUs: 0xFFFFFFFF
Taskset is a command 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.
Installation:
- Debian/Ubuntu systems:
sudo apt-get install util-linux
- Red Hat/ Fedora systems:
sudo yum install util-linux
Usage:
- Retrieve the CPU affinity of a running process:
taskset -p PID
Example:
taskset -p 1276
pid 1276's current affinity mask: 3
- Set the CPU affinity of a running process:
taskset -p MASK PID
Example:
taskset -p 0x00000001 9030
pid 9030's current affinity mask: 3
pid 9030's new affinity mask: 1
- Run a new command with a given CPU affinity:
taskset MASK COMMAND
You can check if taskset is working using top and pressing “1” to show all CPUs.