views:

684

answers:

8

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)

+1  A: 

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

GWLlosa
+1  A: 

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

M4dRefluX
+1  A: 

Here is one way using WMI. Both processor count and whether HT is enabled.

siz
This does not work on one of the target machines, it only reports a single processor even though it is a multicore machine.
Anton
Wow that's a lot of extra code just to check for HT.
M4dRefluX
@Anton: That's interesting. I don't know why that would be the case. If WMI reports one processor, that means windows thinks there's one processor.
siz
+1  A: 

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
+1  A: 

here's a method in WMI:

Hyperthreading

Moose
I googled faster than you did :-D
siz
+2  A: 

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
The link appears to be broken
Anton
I thought HT would be 2 logical processor, 1 physical and a dual core would show 2 logical and 2 physical processors.
siz
A: 

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.

Bevan
A: 

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