Python 3.3+Linuxosfunction
os.sched_getaffinity
os — scheduler (sched)
Return the set of CPUs a process is allowed to run on.
Syntax
os.sched_getaffinity(...)
It returns the set of CPU numbers the process may run on — honouring container limits and taskset. So len(os.sched_getaffinity(0)) sizes a pool better than os.cpu_count. Zero instead of a PID means the current process. Since 3.13 os.process_cpu_count gives a portable answer.
Examples
import os
print(os.sched_getaffinity(0)) # → ? только Unix: множество разрешённых ядер текущего процесса, например {0, 1, 2, 3}
cores = len(os.sched_getaffinity(0)); print(cores) # → ? только Unix: сколько ядер реально доступно процессу, например 4
print(os.cpu_count()) # → ? всего ядер в системе, например 8 — маску процесса не учитывает, в контейнере число завышено
os.sched_setaffinity(0, {0}); print(os.sched_getaffinity(0)) # → ? только Unix: {0} — после сужения маски остаётся одно ядро
print(os.sched_getaffinity(10 ** 7)) # → ProcessLookupError: процесса с таким pid нет
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy