5

I was trying to find a way to get the number of CPU cores somebody has using Python. Almost all the answers I found were either:

multiprocessing.cpu_count()

or

os.cpu_count()

While these options are great for seeing how many threads the computer has, it doesn't tell me how many cores it has.

4
  • By threads, are you referring to HyperThreading pseudo-cores? Because traditionally "threads" means software flows of execution, of which there are usually hundreds running at a time, and can vary from one moment to the next, depending on what programs are executing. Commented Jul 18, 2021 at 4:22
  • When I read the documentation for those functions, it doesn't say anything about threads (I assume you mean pseudo-cores created by hyperthreading). Two questions: 1) Did you test this and get the wrong answer? On what exact architecture? 2) Why exactly does the difference matter for your application? Commented Jul 18, 2021 at 4:24
  • If you are indeed asking about physical vs logical cores, then I will tell you multiprocessing and os will almost always report the number of logical cores. psutil.cpu_count gives you the option to choose which value is reported. Commented Jul 18, 2021 at 4:56
  • 2
    In practice, it is usually advisable to just use the logical cores number anyway, as this is how many hardware instruction pipelines are exposed to the operating system scheduler. It is almost impossible to keep a physical core from stalling with only a single stream of instructions (especially with python), so it is almost always beneficial to use the additional logical cores. It is not a good idea to use more than that however, and leaving one or two logical cores free to work on other system tasks will prevent starving the system of resources completely. Commented Jul 18, 2021 at 5:04

1 Answer 1

11

If you don't mind using a third party library, using psutil will do the trick:

import psutil

print(f'Number of physical cores: {psutil.cpu_count(logical=False)}')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.