How can I set the processor affinity of a process on Linux?
Inside the process, the call would be
sched_setaffinity(), or for pthreads stuff,
On a related note, if you're worrying about CPU affinity of your program, it may be worthwhile to pay attention to how it's doing memory allocation as well. Larger systems with memory attached to more than one controller (i.e. multiple CPU sockets, each with their own) will have variable latency and bandwidth between different CPU-memory pairs. You'll want to look into NUMA affinity as well, using the
numactl command or the system calls that it works with. One program I worked on got a 10% performance improvement from this.
You need to install
schedutils (Linux scheduler utilities).
I have use it on my Ubuntu Desktop.
taskset -c 1-3 ./a.out arg1 arg2
a.out process with given arguments and affinity set to processors 1, 2 or 3 (zero based).
Here is a minimal C test program that can be used to see it in action: https://stackoverflow.com/questions/10490756/how-to-use-sched-getaffinity-and-sched-setaffinity-in-linux-from-c/50117787#50117787