I need to run performance tests for my concurrent program and my requirement is that it should be run on only one CPU core. (I don't want to cooperative threads – I want always have a context switching).
So I have two questions:
-
The best solution – How to sign and reserve only one CPU core only for my program (to force OS to not use this CPU core). I guess it is not possible but maybe I'm wrong…
-
How to set linux (Fedora 24) to use only one CPU core?
Best Answer
On linux, the system call to set the CPU affinity for a process is
sched_setaffinity
. Then there's thetaskset
tool to do it on the command line.To have that single program run on only one CPU, I think you'd want something like
(set any CPU number as an argument to the
-c
switch.)That should be close enough to a single-processor system, as long as your other processes don't run too much compared to the one you want to measure, or they get scheduled to other CPU's. If you want to dedicate one CPU to that single process only, and prevent other processes from running on that CPU, you'd need to set their affinity too.
That, I don't know how to do properly. You'd need to set the processor affinity of
init
very early in the boot process to make sure it gets inherited to all processes on the system. As a workaround, you could usetaskset -c -p 0 $PID
for all other processes to force them to run on CPU #0 only.systemd also has
CPUAffinity=
to control the affinity in unit files and there are a couple of questions on setting the default affinity here on unix.SE, but I didn't find any with a good solution.Though as @Kamil Maciorowski commented and answered to another question on superuser.com, setting
isolcpus=1
on the kernel command line should "isolate that CPU from the general scheduling algorithms", which is something you may want.