确定物理处理器/核心数量
为了获得最佳性能,多线程应用程序需要精确的物理处理器或核心数量。检测逻辑处理器的数量是不够的,特别是考虑到超线程,其中多个逻辑线程在单个物理核心上运行。
检测超线程支持和激活
要准确计数对于物理处理器,确定是否支持并启用超线程至关重要。这需要检查CPUID指令的EDX寄存器的位28。如果设置该位,则支持超线程。然而,仅仅确认支持是不够的;
使用 CPUID 指令实现
提出了使用 CPUID 指令的全面 C 解决方案:
<code class="cpp">#include <iostream> #include <string> void cpuID(unsigned i, unsigned regs[4]) { ... } int main() { unsigned regs[4]; char vendor[12]; // Get vendor cpuID(0, regs); ((unsigned *)vendor)[0] = regs[1]; ((unsigned *)vendor)[1] = regs[3]; ((unsigned *)vendor)[2] = regs[2]; string cpuVendor = string(vendor, 12); // Get CPU features cpuID(1, regs); unsigned cpuFeatures = regs[3]; // Logical core count per CPU cpuID(1, regs); unsigned logical = (regs[1] >> 16) & 0xff; unsigned cores = logical; // Determine core count based on vendor if (cpuVendor == "GenuineIntel") { cpuID(4, regs); cores = ((regs[0] >> 26) & 0x3f) + 1; } else if (cpuVendor == "AuthenticAMD") { cpuID(0x80000008, regs); cores = ((regs[2] & 0xff)) + 1; } // Detect hyper-threads bool hyperThreads = cpuFeatures & (1 << 28) && cores < logical; // Display results cout << " logical cpus: " << logical << endl; cout << " cpu cores: " << cores << endl; cout << "hyper-threads: " << (hyperThreads ? "true" : "false") << endl; return 0; }</code>
输出示例
在不同的 Intel 系统上运行时,程序输出:
Core 2 Duo T7500:
logical cpus: 2 cpu cores: 2 hyper-threads: false
Core 2 Quad Q8400:
logical cpus: 4 cpu cores: 4 hyper-threads: false
Xeon E5520(双 CPU 套件):
logical cpus: 16 cpu cores: 8 hyper-threads: true
奔腾 4 3.00GHz:
logical cpus: 2 cpu cores: 1 hyper-threads: true
以上是如何确定系统中物理处理器或内核的实际数量?的详细内容。更多信息请关注PHP中文网其他相关文章!