Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of CPU's logical cores/threads in C#?

How I can get number of logical cores in CPU?

I need this to determine how many threads I should run in my application.

like image 992
Kamil Avatar asked Oct 22 '12 16:10

Kamil


People also ask

How do you find the number of logical cores?

Press Ctrl + Shift + Esc to open Task Manager. Select the Performance tab to see how many cores and logical processors your PC has.

How many logical processors are there in a 4 core CPU?

The logical processor (logical core or CPU) is how many of those cores are divided using hyperthreading to allow multiple instructions (threads) to be processed on each core simultaneously. For example, your processor may have four physical cores that are divided into eight logical processors using hyperthreading.


2 Answers

You can get number of logical processors through the Environment class
number of 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);

number of logical processors

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}


Environment.ProcessorCount

 using System;

 class Sample 
 {
     public static void Main() 
     {
        Console.WriteLine("The number of processors on this computer is {0}.", 
           Environment.ProcessorCount);
     }
 }

go through this link http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx

like image 135
Ravindra Bagale Avatar answered Oct 05 '22 10:10

Ravindra Bagale


Use the Environment.ProcessorCount property, it returns the number of logical cores.

like image 25
Mike Taylor Avatar answered Oct 05 '22 08:10

Mike Taylor