Title: Use WMI to get the number of physical and logical processors in C#
This example shows how you can determine your computer's number of processors, both physical and logical.
Many computers these days contain multiple CPUs. Each CPU may contain multiple cores, processors that can execute instructions. Finally, some cores can execute multiple streams of execution simultaneously. And all of this is separate from the multi-threading used by the operating system, where the system quickly switches back and forth among threads to make it seem like different programs are running at the same time.
All of that makes it confusing to figure out exactly how many threads of execution can be running truly simultaneously. The following GetProcessorCounts method returns the number of physical processors, the number of cores, and the number of logical processors.
// Return the numbers of physical processors, cores,
// and logical processors.
private void GetProcessorCounts(out int num_physical_processors,
out int num_cores, out int num_logical_processors)
{
string query;
ManagementObjectSearcher searcher;
// Get the number of physical processors.
num_physical_processors = 0;
query = "SELECT * FROM Win32_ComputerSystem";
searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject sys in searcher.Get())
num_physical_processors =
int.Parse(sys["NumberOfProcessors"].ToString());
// Get the number of cores.
query = "SELECT * FROM Win32_Processor";
num_cores = 0;
searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject proc in searcher.Get())
num_cores += int.Parse(proc["NumberOfCores"].ToString());
num_logical_processors = Environment.ProcessorCount;
}
The method first uses WMI to select Win32_ComputerSystem information. It uses the returned object's NumberOfProcessors property to get the number of physical processors on the system.
Next the method uses WMI to select Win32_Processor information. Each of those objects represents a physical processor. (So the number of objects returned should equal the number of physical processors the method just calculated.) The code loops through the returned processor objects and adds up their numbers of cores.
Finally the code uses Environment.ProcessorCount to get the logical number of processors. This includes all of the threads that could be running at the same time on all processors and cores. Usually this is all you care about in a program. It should also usually equal:
(# processors) × (# cores per processor) × (# threads per core)
For example, my system has a single Intel i7-11390H processor with 4 cores each running 2 threads for a total of 1 × 4 × 2 = 8 threads.
Download the example to experiment with it and to see additional details.
|