Hi,
Is there a way via .NET/C# to find out the number of CPU cores?
Thanks!
PS This is a straight code question, not a "Should I use multi-threading?" question! :-)
Hi,
Is there a way via .NET/C# to find out the number of CPU cores?
Thanks!
PS This is a straight code question, not a "Should I use multi-threading?" question! :-)
Environment.ProcessorCount should give you the number of cores on the local machine.
There are several different pieces of information relating to processors that you could get: number of physical processors, number of cores, number of logical processors. These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.
The number of logical processors is available through the Environment
class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):
Physical Processors:
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}
Cores:
int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);
Logical Processors:
Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);
OR
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}