How to get number of CPU's logical cores/threads in C#?
17,839
Solution 1
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
Solution 2
Use the Environment.ProcessorCount property, it returns the number of logical cores.
Author by
Kamil
Electrican by education Electronics engineer by hobby Programmer (some languages professionally, some by hobby) Windows Server admin - few years of experience Sorry for my grammar and spelling errors, feel free to correct them by editing my posts.
Updated on June 25, 2022Comments
-
Kamil almost 2 years
How I can get number of logical cores in CPU?
I need this to determine how many threads I should run in my application.
-
Kamil over 11 yearsI have no ManagementObjectSearcher object in System.Management. Why?
-
Ravindra Bagale over 11 years@Kamil: check Assembly: System.Management (in System.Management.dll)
-
Ravindra Bagale over 11 years@Kamil: check it is in System.ComponentModel.Component
-
Kamil over 11 yearsI tried Environment.ProcessorCount, looks OK, i have 2 cores detected on Core Duo T2500 CPU. I have to try this on quad core xeon with HT.
-
Kamil over 11 yearsI found and added reference to that dll. It also works, but much slower than Environment.ProcessorCount. What is the difference? I know why WMI technique works slower, but can results differ? Will Win32_ComputerSystem work on Windows 64?
-
Kamil over 11 yearsThanks @MikeT, but i had to accept answer that took author little more time. Your answer is satisfying too.