在C#开发中,有时候我们需要获取当前系统CPU的核心数,关于CPU的核心数,主要有物理处理器(Physical Processors)的个数、CPU核心(Cores)的个数和逻辑处理器(Logical Processors)的个数三种。
比如,使能了超线程的2个双核心的处理器,有2个物理处理器,4个内核,和8个逻辑处理器。其中逻辑处理器的个数,在C#中可以通过Environment类获取,但其他CPU信息只能通过WMI来获取了。
物理处理器(Physical Processors)个数获取的参考代码:
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}
CPU核心数(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);
CPU逻辑处理器(Logical Processors)个数获取的参考代码:
Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);
//或者
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}
评论区