The standard method that I know to get number of cores in python is to use multiprocess.cpu_count
import multiprocessing
print(multiprocessing.cpu_count())
Also, when creating a task we can specify some cores that the process can access using taskset.
Apparently cpu_count
is always getting the number of available cores of the machine, regardless if the process was restricted to use only some of those cores.
python nproc.py
taskset 7 python nproc.py
taskset 1 python nproc.py
nproc on the other hand gives the number of cores available for the process.
taskset 7 nproc # gives at most 3
taskset 1 nproc # gives 1
I know I could invoke nproc
or taskset -p {os.getpid()}
to get the correct number of cores. Is there another way to do this, without relying on other programs (reading
/proc/{os.pid()}/*
could be a solution).
Thank you