What is CPU affinity ? Binding or unbinding one or more processes to one or more processors called CPU affinity. It enables that process(es) runs only designated processor(s) rather than any processor. There are two types of CPU affinity, which are soft affinity and hard affinity. Soft affinity is a mechanism that keeping process on the same CPU as long as possible otherwise, process is migrated to other processor. Hard affinity is a mechanism that enables processes can run only on a fixed set of one or more processor(s).
Benefits of CPU affinity
- Optimizes cache performance as the process runs on the same CPU core and no cache invalidation happens. (NUMA architecture.)
- Time-sensitive, and real time applications. Due to the fact that those applications will run only designated cores. And scheduler runs other applications on the other processors. How to Implement CPU affinity in Linux ? In Linux, you can set CPU affinity with taskset or numactl command. In this post I will use taskset command. taskset -c <cpu core(s)> To run a nvpy, which is python based note taking application, on the only core 0.
taskset -c 0 nvpy
To set cpu affinity for a running process. First we need to find pid.
gokay@ankara:~$ pgrep nvpy 26119
Set CPU affinity to core 3 for running process whose pid is 26119.(nvpy)
gokay@ankara:~$ taskset -pc 3 26119 pid 26119's current affinity list: 0 pid 26119's new affinity list: 3 gokay@ankara:~$
Showing process (26119) and its threads of CPUs currently running on.
gokay@ankara:~$ ps -T -p 26119 -o pid,spid,psr PID SPID PSR 26119 26119 3 26119 26121 0 26119 26122 0 26119 26123 0
Note: If you do not know what to do please leave it to OS scheduler. Otherwise your application may suffer from compute resources.