开发者

C/C++/Assembly Programatically detect if hyper-threading is active on Windows, Mac and Linux [duplicate]

开发者 https://www.devze.com 2022-12-31 07:34 出处:网络
This question already has answers here: How to Detect the Number of Physical Processors / Cores on Windows, Mac and Linux
This question already has answers here: How to Detect the Number of Physical Processors / Cores on Windows, Mac and Linux (14 answers) Closed 9 years ago.

I can already correctly detect the number of logical processors correctly on all three of these platforms.

To be able to detect the number of physical processors/cores correctly I'll have to detect if hyperthreading is supported AND active (or enabled if you prefer) and if so divide the number of logical processors by 2 to determine the number of physical开发者_如何学Python processors.

Perphaps I should provide an example:

A quad core Intel CPU's with hyperthreading enabled has 4 physical cores, yet 8 logical processors (hyperthreading creates 4 more logical processors). So my current function would detect 8 instead of the desired 4.

My question therefore is if there is a way to detect whether hyperthreading is supported AND ENABLED?


On Windows 2003 Server and Windows XP SP3 and later, you can determine this information using the GetLogicalProcessorInformation system call.


The CPUID instruction (when you pass function 1H in EAX) returns they hyper threading feature flag in bit 28 of the EDX register. I think that multi-core processors report that they are hyperthreading enabled even though each individual core can run only one thread.

It also returns the number of logical processors per physical processor in bits 23-16 of EBX. I think that you'd have to query each processor individually in order to hit all of the processors on your system.


Linux:

Number of physical CPUs:

grep -i "physical id" /proc/cpuinfo | sort -u | wc -l

Number of logical CPUs:

grep -i "processor" /proc/cpuinfo | sort -u | wc -l


On OS X:

#include <sys/sysctl.h>

int physicalCores;
sysctlbyname("hw.physicalcpu", &physicalCores, sizeof(physicalCores), NULL, 0);

See the header or manpage for more information. (Note that you can get the number of logical cpus in the same way, using the "hw.logicalcpu" string)

0

精彩评论

暂无评论...
验证码 换一张
取 消