Taskset Command for CPU Affinity in Linux
This article provides an overview of the Linux taskset
command, detailing how it manages CPU affinity by binding processes to
specific processor cores. It covers the core functionality of the
command, the concept of processor affinity, practical command syntax for
both running and new processes, and the performance benefits of
controlling CPU scheduling.
Understanding CPU Affinity
CPU affinity, or processor affinity, is a scheduling feature that binds a process or thread to one or more designated CPU cores. By default, the Linux kernel scheduler dynamically assigns tasks to any available CPU core to balance the overall system workload. However, frequently moving a process between different cores can lead to performance overhead due to CPU cache invalidation. Setting CPU affinity ensures that a process runs exclusively on the assigned cores, preserving cache locality and reducing latency.
The Function of the taskset Command
The taskset command is a standard Linux utility (part of
the util-linux package) used to retrieve and manipulate the
CPU affinity of a process. It operates either by modifying the CPU mask
of an already running process using its Process ID (PID) or by launching
a new process with a predefined core assignment.
CPU affinity can be specified in two formats:
- Bitmask: A hexadecimal representation where each
bit corresponds to a CPU core (e.g.,
0x00000001for CPU 0,0x00000003for CPUs 0 and 1). - CPU List: A comma-separated or hyphenated list of
core numbers using the
-cor--cpu-listflag (e.g.,0,2,3or0-3), which is more human-readable.
Common Usage and Syntax
Checking the Current Affinity of a Process
To view which cores are assigned to an active process:
taskset -p <PID>To display the affinity in a readable core list format:
taskset -cp <PID>Changing the Affinity of a Running Process
To reassign an existing process to specific cores (such as cores 1 and 3):
taskset -cp 1,3 <PID>Launching a Process with Specific Affinity
To start an application bound strictly to designated cores (for example, cores 0 and 2):
taskset -c 0,2 <command> <arguments>Key Use Cases and Benefits
- Cache Optimization: Keeping high-throughput tasks on specific cores maximizes L1 and L2 cache hits, significantly reducing memory access latency.
- Workload Isolation: Critical services (such as databases or real-time trading engines) can be pinned to dedicated cores, isolating them from general system processes.
- NUMA Architecture Tuning: On Non-Uniform Memory
Access (NUMA) systems,
tasksetensures that tasks run on cores directly attached to the local memory node they access most frequently, avoiding interconnect bottlenecks. - Benchmarking and Testing: Developers use
tasksetto eliminate scheduling variability when profiling code performance under consistent hardware conditions.