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

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

王林
Release: 2023-09-14 22:21:02
forward
1380 people have browsed it

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();
   }
}
Copy after login

Output

Number Of Physical Processors: 1
Copy after login

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();
   }
}
Copy after login

Output

Number Of Cores: 2
Copy after login

Logical Processor

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

Output

Number Of Logical Processors: 4
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template