+ 1

How can you get number of PHYSICAL CPU cores using code?

I'm using c++ but any programming language that solves this would be great. Logical cores != physical cores because of Intel's hyperthreading and AMD's Simultaneous Multi Threading (SMT). Getting the logical core count is easy enough. Even browser-based JavaScript can get it with navigator.hardwareConcurrency. That's why I'm asking specifically about PHYSICAL cores. Here is a very similar question but the answers are all obsolete and don't work. Some answers are one-liners but retrieve "Logical" not "Physical" cores: https://stackoverflow.com/questions/2901694/how-to-detect-the-number-of-physical-processors-cores-on-windows-mac-and-linu Here is a similar question asking for a JavaScript solution but none of the answers work for "Physical" cores. https://stackoverflow.com/questions/3289465/get-number-of-cpu-cores-in-javascript I want to get this value to help a program find the best number of threads to use without pushing the OS and CPU into wasteful timeslicing and context switching. Running as many CPU-bound threads as there are logical cores performs slightly worse than matching the number of physical cores.

27th Feb 2020, 8:10 PM
Josh Greig
Josh Greig - avatar
3 Answers
+ 2
Since nobody has answered yet.. The winapi has what you are searching: https://docs.microsoft.com/de-de/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation Check their code example below for how to access the physical(?) number of cores. I'm not sure what physical means these days.
28th Feb 2020, 1:25 AM
Schindlabua
Schindlabua - avatar
0
Python has a library called psutil - in it there's a function called cpu_count which checks for logical ones by default, so: psutil.cpu_count(logical=False) Should output what you're looking for..? Hope it helps! https://psutil.readthedocs.io/en/latest/#psutil.cpu_count If you need the output I'm pretty sure you can run the .py with commands and retrieve the result with c++
28th Feb 2020, 3:40 AM
LDSD
LDSD - avatar