在多线程应用程序中,每个物理处理器核心使用一个线程可确保最佳性能。为了精确确定线程数,区分物理核心和超线程核心至关重要。以下是如何在 Windows、Mac 和 Linux 上检测超线程支持及其激活状态:
利用 CPUID 指令,我们可以收集有关处理器功能和配置的信息。分步过程概述如下:
物理核心Count:
这里是一个 C实现该方法的程序:
#include
#include
void cpuID(unsigned i, unsigned regs[4]);
int main() {
unsigned regs[4];
// Get CPUID information
cpuID(0x00, regs);
cpuID(0x01, regs);
// Determine vendor
char vendor[12];
((unsigned *)vendor)[0] = regs[1];
((unsigned *)vendor)[1] = regs[3];
((unsigned *)vendor)[2] = regs[2];
std::string cpuVendor = std::string(vendor, 12);
// Variables
unsigned logicalCores = (regs[1] >> 16) & 0xff;
unsigned cores = logicalCores;
bool hyperThreads = false;
// Detect hyper-threading
if (cpuVendor == "GenuineIntel") {
cpuID(0x04, regs);
cores = ((regs[0] >> 26) & 0x3f) 1;
} else if (cpuVendor == "AuthenticAMD") {
cpuID(0x80000008, regs);
cores = ((unsigned)(regs[2] & 0xff)) 1;
}
if (regs[3] & (1 输出示例:
Intel Core 2 Duo E8400(无超线程):
Logical cores: 2
Cores: 2
Hyper-threading: false
Intel Core i7-7700K(带超线程):
Logical cores: 8
Cores: 4
hyper-threads: true
AMD Ryzen 5 2600X(带 SMT):
Logical cores: 12
Cores: 6
hyper-threads: true
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3