How to get the number of threads per cores in python

Viewed 4980

My computers CPU has 4 cores and 2 threads for each core, as I can get it by lscpu command:

Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   48 bits physical, 48 bits virtual
CPU(s):                          4
On-line CPU(s) list:             0-3
Thread(s) per core:              2
...

I can get the numbers of cores by multiprocessing.cpu_count() python standard. But i can't find any way to get the number of threads per core by python. I know i can execute lscpu command and get the number of threads by parsing the output in python. But Is there any standard solution?

2 Answers

You can use psutil module in python3.

python3 -m pip install psutil

The psutil.cpu_count method returns the number of logical CPUs in the system (same as os.cpu_count in Python 3.4) or None if undetermined. logical cores means the number of physical cores multiplied by the number of threads that can run on each core (this is known as Hyper Threading). If logical is False return the number of physical cores only (Hyper Thread CPUs are excluded) or None if undetermined.

import psutil

threads_count = psutil.cpu_count() / psutil.cpu_count(logical=False)

[edit]: If you only need the tread count per core, you can do like this (OSX and linux):

import psutil
print(f'thread count per core: {psutil.cpu_count() // psutil.cpu_count(logical=False)}')

You will have to try if this works on windows, I have no way to tell.


On linux you can do like this to run your command from python, with the subprocess module from the standard library:

p = subprocess.run(['lscpu'], capture_output=True, text=True)
print(f'lscpu: {p.stdout}')

This command does not exist on OSX, and IDK for windows.

Related