taskset Cheatsheet

CPU affinity & process pinning

Linux
Contents
🔧

Basics

# Run command on specific CPU(s)
taskset -c 0 command        # CPU 0 only
taskset -c 0,1 command      # CPU 0 and 1
taskset -c 0-3 command      # CPU 0 through 3

# -c flag = CPU list (human readable)
# Without -c = hex bitmask

# Check number of CPUs
nproc
lscpu | grep "CPU(s)"
cat /proc/cpuinfo | grep processor | wc -l
🎭

CPU Mask (Hex Bitmask)

# Hex bitmask: each bit = one CPU
# CPU 0 →  0x1  (binary: 0001)
# CPU 1 →  0x2  (binary: 0010)
# CPU 2 →  0x4  (binary: 0100)
# CPU 3 →  0x8  (binary: 1000)

# Combinations:
# CPU 0,1   → 0x3  (0011)
# CPU 0,2   → 0x5  (0101)
# CPU 0-3   → 0xF  (1111)
# CPU 0-7   → 0xFF
# All CPUs  → 0xFFFFFFFF

# Using mask directly
taskset 0x3 command   # CPUs 0,1
taskset 0xF command   # CPUs 0-3
📌

Set Affinity

# Set for running process
taskset -p -c 0 1234      # PID 1234 → CPU 0
taskset -p -c 0-3 1234    # PID 1234 → CPUs 0-3
taskset -p 0xF 1234       # hex mask

# Start new process pinned
taskset -c 2 ./myapp
taskset -c 4-7 python3 script.py

# Pin to NUMA node (numactl)
numactl --cpunodebind=0 command
numactl --membind=0 command
🔍

Get Affinity

# Get affinity of PID
taskset -p 1234
# Output: pid 1234's current affinity mask: f

# With CPU list
taskset -cp 1234
# Output: pid 1234's current affinity list: 0-3

# All processes affinity
for pid in $(ls /proc/ | grep -E '^[0-9]+$'); do
  taskset -cp $pid 2>/dev/null
done

# Check via /proc
cat /proc/1234/status | grep Cpus_allowed
🏗️

cgroups & isolcpus

# Kernel boot param: isolate CPUs from scheduler
# Add to GRUB_CMDLINE_LINUX:
isolcpus=2,3

# cgroups v2 (systemd):
systemctl set-property myservice.service AllowedCPUs=0,1

# cgroups manual:
echo "0-1" > /sys/fs/cgroup/mygroup/cpuset.cpus
echo "0" > /sys/fs/cgroup/mygroup/cpuset.mems
echo $$ > /sys/fs/cgroup/mygroup/cgroup.procs

# Docker CPU pinning
docker run --cpuset-cpus="0,1" myimage
💡

Practical Examples

# Pin database to CPUs 0-3
taskset -c 0-3 mysqld

# Pin web server to CPUs 4-7
taskset -c 4-7 nginx

# Benchmark on single core
taskset -c 0 ./benchmark

# Real-time process on isolated CPU
taskset -c 3 chrt -f 99 ./rt_app

# Python multiprocessing
taskset -c 0-3 python3 -c "
import os
os.sched_getaffinity(0)  # {0, 1, 2, 3}
os.sched_setaffinity(0, {0, 1})
"

# Monitor CPU usage per core
mpstat -P ALL 1