2

I have some code that needs to know how many actual cores are available on my particular machine, and whether or not Hyperthreading is enabled.

Is there a way to do this in C#?

Update: The machines are a mix of XP and Vista

Update: Accessing 'Win32_Processor.NumberOfCores' or 'Win32_Processor.NumberOfLogicalProcessors' throws an exception (a ManagmentException with the message "Not Found") on one of the machines (but not all of them)

Anton
  • 6,860
  • 12
  • 30
  • 26

6 Answers6

3

On Vista and higher you can use GetLogicalProcessorInformation via PInvoke to get the number of logical processor units.

On Windows XP there's no way via C# to reliably differentiate hyper-threading from other multi-processor/core configurations. The WMI solution that someone posted will class multi-core processors as hyper-threaded.

Prior to Vista the only reliable means is to check the CPUID of the processor. To use this you could create a native DLL that can be called from your managed code. The following Intel code sample would be a good starting point.

Andrew Grant
  • 58,260
  • 22
  • 130
  • 143
2

Simple answer to the first question at least: Environment.ProcessorCount should return the number of cores on the machine.

Edit: Here's a non-WMI-based method of checking for whether Hyperthreading is enabled (not that it's any nicer necessarily). Also see this article.

Noldorin
  • 144,213
  • 56
  • 264
  • 302
1

System.Environment.ProcessorCount will tell you how many cores exist on the machine the code is running on.

GWLlosa
  • 23,995
  • 17
  • 79
  • 116
1

Check the Environment.ProcessorCount property, it will return an integer, as far as HyperThreading, I'm not sure.

Steven DeWitt
  • 1,829
  • 1
  • 21
  • 23
0

StackOverflow question 188503 has the information you need ...

Quoting the top answer on that question:

System.Environment.ProcessorCount

returns the number of logical processors (see MSDN)

To distinguish between Hyperthreaded and separate cores, sounds as though you need a bit of WMI.

Community
  • 1
  • 1
Bevan
  • 43,618
  • 10
  • 81
  • 133
0

GetLogicalProcessorInformation is sufficient for the HT aspect but sadly it is only available in XP SP3, 64bit XP/Vista/Server 2003 (and I believe is is slightly broken pre vista)

Joe Duffy wrapped this in c# but has not yet released the source, though Mark Russinovich has released the tool (Coreinfo) he created with it, likely you can decompile that to see the code.

ShuggyCoUk
  • 36,004
  • 6
  • 77
  • 101