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

孤者浪人 提交于 2019-11-30 17:00:28

问题


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 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?


回答1:


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



回答2:


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




回答3:


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.




回答4:


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)



来源:https://stackoverflow.com/questions/2904283/c-c-assembly-programatically-detect-if-hyper-threading-is-active-on-windows-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!