在多執行緒應用程式中,每個實體處理器核心使用一個執行緒可確保最佳效能。為了精確確定線程數,區分物理核心和超線程核心至關重要。以下是如何在 Windows、Mac 和 Linux 上偵測超執行緒支援及其啟動狀態:
利用 CPUID 指令,我們可以收集有關處理器功能和配置的資訊。逐步流程概述如下:
物理核心數:
這是一個實現此方法的C 程序:
<code class="cpp">#include <iostream> #include <string> 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 << 28) && cores < logicalCores) { hyperThreads = true; } // Print results std::cout << "Logical cores: " << logicalCores << std::endl; std::cout << "Cores: " << cores << std::endl; std::cout << "Hyper-threading: " << (hyperThreads ? "true" : "false") << std::endl; return 0; }</code>
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
以上是如何確定Windows、Mac和Linux上是否啟用了超執行緒?的詳細內容。更多資訊請關注PHP中文網其他相關文章!