Home  >  Article  >  Backend Development  >  How to find the number of CPU cores in C#?

How to find the number of CPU cores in C#?

王林
王林forward
2023-09-14 22:21:021256browse

How to find the number of CPU cores in C#?

We can get a lot of different information related to the processor

  • Number of physical processors
  • Number of cores
  • Number of logical processors

These can all be different; take a machine with 2 dual-core hyperthreading enabled as an example Processors, with 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors can be obtained through the Environment class, but Additional information is only available through WMI (and you may need to install some On some systems, a hotfix or service pack needs to be installed for operation) −

Add a reference to System.Management.dll in your project. In .NET Core, this is provided as a NuGet package (Windows only).

Physical Processor

Example

class Program{
   public static void Main(){
      foreach (var item in new
      System.Management.ManagementObjectSearcher("Select * from
      Win32_ComputerSystem").Get()){
         Console.WriteLine("Number Of Physical Processors: {0} ",
         item["NumberOfProcessors"]);
      }
      Console.ReadLine();
   }
}

Output

Number Of Physical Processors: 1

Core

class Program{
   public static void Main(){
      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);
      Console.ReadLine();
   }
}

Output

Number Of Cores: 2

Logical Processor

class Program{
   public static void Main(){
      Console.WriteLine("Number Of Logical Processors: {0}",
      Environment.ProcessorCount);
      Console.ReadLine();
   }
}

Output

Number Of Logical Processors: 4

The above is the detailed content of How to find the number of CPU cores in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete