Determining Physical Processor/Core Count
For optimal performance, multithreaded applications require a precise count of physical processors or cores. Detecting the number of logical processors is insufficient, especially considering hyperthreading, where multiple logical threads run on a single physical core.
Detecting Hyperthreading Support and Activation
To accurately count physical processors, it's crucial to determine if hyperthreading is supported and enabled. This requires examining the CPUID instruction's EDX register's bit 28. If this bit is set, hyperthreading is supported. However, simply confirming support is insufficient; the bit must also be active.
Implementation using CPUID Instruction
A comprehensive C solution using the CPUID instruction is presented:
<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>
Output Examples
When run on different Intel systems, the program outputs:
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 (dual CPU packages):
logical cpus: 16 cpu cores: 8 hyper-threads: true
Pentium 4 3.00GHz:
logical cpus: 2 cpu cores: 1 hyper-threads: true
The above is the detailed content of How to Determine the Actual Number of Physical Processors or Cores in a System?. For more information, please follow other related articles on the PHP Chinese website!