In this blog entry
we're not going to explain how you can accomplish something using Adam. Instead,
we're going to talk about how we've developed something in Adam internally. To
be precise, we'll explain what we've done to determine the number of physical CPU's used by Windows. But we're not only going to talk about how we've done it; we're going
to give you the code as well.
Typically, if people want to learn how many CPU's there are in a server using
.NET code (like C#), they will use the value returned by the
System.Environment.ProcessorCount property. The problem with this property
however is that it returns the number of CPU's detected by Windows and nowadays
this is typically not the same as the number of physical CPU's since practically
all CPU's use are multi-core or use hyperthreading. The .NET Framework 2.0 does not have a property that returns this information.
First of all, if you're going to search the Internet for resources on how to do
this, you're going to mostly find two different answers. You'll find people
telling you to use WMI tor determine this and you're going to find people
telling you to use the Windows API. The problem with the WMI solution is that -
at least on Windows XP and Windows Server 2003 - it is a completely unreliable
solution. WMI gives you the wrong answer more often than not. As far as the
Windows API solution is concerned, most of the times the sample code that you'll
find on the Internet will not be complete or will not work on 64-bit. The code
below has proven (for us at least) to work reliably on:
- Windows Server 2003 SP2 and higher (32-bit and 64-bit)
- Windows Server 2008 (32-bit and 64-bit)
- Windows XP SP3 (32-bit)
- Windows Vista (32-bit and 64-bit)
As we mentioned, earlier versions of Adam 4 used the WMI (the Windows Management
Instrumentation framework) to determine the number of physical CPU's in a
machine. For people that want to know, this is the code (but know that this will
not work reliably):
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
Dictionary<string, string> oSockets = new Dictionary<string, string>();
System.Management.ManagementClass oProcessorClass =
new System.Management.ManagementClass("Win32_Processor");
System.Management.ManagementObjectCollection oProcessors =
oProcessorClass.GetInstances();
foreach (System.Management.ManagementObject oObject in oProcessors)
{
object oSocket = oObject["SocketDesignation"];
if (oSocket != null)
{
oSockets[oSocket.ToString()] = null;
}
}
int iCpus = oSockets.Count;
|
So, the better solution is to use the Windows API to query the processor directly. The difficulty
implementing this solution is that you need to do some work to make it work on
32-bit and 64-bit. Also, the SYSTEM_LOGICAL_PROCESSOR_INFORMATION
structure returned by the GetLogicalProcessorInformation function
contains a C++ union which is a bit difficult to work with in C#. What we've
done is we've created two versions of this struct in C#, one for 32-bit and one
for 64-bit, both use FieldOffset-attributes to ensure that we can
reliably access the values of this struct on both platforms.
But enough said, this is the .NET 2.0 C# code to determine how many physical
cpu's a Windows machine is using:
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace CpuCount
{
public static class Machine
{
private const int ERROR_INSUFFICIENT_BUFFER = 122;
private enum PROCESSOR_CACHE_TYPE
{
/// <summary>
/// The cache is unified.
/// </summary>
UnifiedCache = 0,
/// <summary>
/// InstructionThe cache is for processor instructions.
/// </summary>
InstructionCache = 1,
/// <summary>
/// The cache is for data.
/// </summary>
DataCache = 2,
/// <summary>
/// TraceThe cache is for traces.
/// </summary>
TraceCache = 3
}
[StructLayout(LayoutKind.Sequential)]
private struct CACHE_DESCRIPTOR
{
byte Level;
byte Associativity;
UInt16 LineSize;
UInt32 Size;
[MarshalAs(UnmanagedType.U4)]
PROCESSOR_CACHE_TYPE Type;
}
private enum RelationProcessorCore
{
/// <summary>
/// The specified logical processors share a
/// single processor core.
/// </summary>
RelationProcessorCore = 0,
/// <summary>
/// The specified logical processors are part
/// of the same NUMA node.
/// </summary>
RelationNumaNode = 1,
/// <summary>
/// The specified logical processors share a cache.
/// Windows Server 2003: This value is not supported
/// until Windows Server 2003 SP1 and Windows XP
/// Professional x64 Edition.
/// </summary>
RelationCache = 2,
/// <summary>
/// The specified logical processors share a physical
/// package (a single package socketed or soldered
/// onto a motherboard may contain multiple processor
/// cores or threads, each of which is treated as a
/// separate processor by the operating system).
/// Windows Server 2003: This value is not
/// supported until Windows Vista.
/// </summary>
RelationProcessorPackage = 3
}
[StructLayout(LayoutKind.Explicit)]
private struct SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx86
{
[FieldOffset(0)]
public uint ProcessorMask;
[FieldOffset(4), MarshalAs(UnmanagedType.U4)]
public RelationProcessorCore Relationship;
[FieldOffset(8)]
public byte Flags;
[FieldOffset(8)]
public CACHE_DESCRIPTOR Cache;
[FieldOffset(8)]
public UInt32 NodeNumber;
[FieldOffset(8)]
public UInt64 Reserved1;
[FieldOffset(16)]
public UInt64 Reserved2;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetLogicalProcessorInformation(
[Out] SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx86[] infos,
ref uint infoSize);
[StructLayout(LayoutKind.Explicit)]
private struct SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx64
{
[FieldOffset(0)]
public uint ProcessorMask;
[FieldOffset(8), MarshalAs(UnmanagedType.U4)]
public RelationProcessorCore Relationship;
[FieldOffset(12)]
public byte Flags;
[FieldOffset(12)]
public CACHE_DESCRIPTOR Cache;
[FieldOffset(12)]
public UInt32 NodeNumber;
[FieldOffset(12)]
public UInt64 Reserved1;
[FieldOffset(20)]
public UInt64 Reserved2;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetLogicalProcessorInformation(
[Out] SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx64[] infos,
ref uint infoSize);
private class ProcessorInfo
{
private RelationProcessorCore _Relationship;
private byte _Flags;
private uint _ProcessorMask;
public ProcessorInfo(RelationProcessorCore relationShip,
byte flags, uint processorMask)
{
_Relationship = relationShip;
_Flags = flags;
_ProcessorMask = processorMask;
}
public RelationProcessorCore Relationship
{
get
{
return _Relationship;
}
}
public byte Flags
{
get
{
return _Flags;
}
}
public uint ProcessorMask
{
get
{
return _ProcessorMask;
}
}
}
/// <summary>
/// Gets <b>true</b> if this process is running in a 64 bit
/// environment, <b>false</b> otherwise.
/// </summary>
public static bool Is64BitProcess
{
get
{
return Marshal.SizeOf(typeof(IntPtr)) == 8;
}
}
/// <summary>
/// Gets <b>true</b> if this is a 64 bit Windows.
/// </summary>
public static bool Is64BitWindows
{
get
{
// The purpose is to know if we're running in pure 32-bit
// or if we're running in an emulated 32-bit environment.
// Earlier versions of this method checked for the existence
// of the HKLM\Software\Wow6432Node node, but this turned
// out to be not realiable. Apparently, this node can exist
// on a 32-bit Windows as well.
try
{
string sArchitecture = Environment.GetEnvironmentVariable(
"PROCESSOR_ARCHITECTURE", EnvironmentVariableTarget.Machine);
if (sArchitecture == null)
{
return false;
}
else
{
return sArchitecture.Contains("64");
}
}
catch (NotSupportedException)
{
return false;
}
catch (ArgumentException)
{
return false;
}
}
}
/// <summary>
/// Returns <b>true</b> if this is a 32-bit process
/// running on a 64-bit server.
/// </summary>
public static bool IsWow64Process
{
get
{
return Machine.Is64BitWindows && !Machine.Is64BitProcess;
}
}
private static List<ProcessorInfo> GetProcessorInfo86()
{
// First we're going to execute GetLogicalProcessorInformation
// once to make sure that we determine the size of the data
// that it is going to return.
// This call should fail with error ERROR_INSUFFICIENT_BUFFER.
uint iReturnLength = 0;
SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx86[] oDummy = null;
bool bResult = GetLogicalProcessorInformation(oDummy,
ref iReturnLength);
if (bResult)
{
throw Fail("GetLogicalProcessorInformation failed.", "x86");
}
// Making sure that the error code that we got back isn't that
// there is insufficient space in the buffer.
int iError = Marshal.GetLastWin32Error();
if (iError != ERROR_INSUFFICIENT_BUFFER)
{
throw Fail(
"Insufficient space in the buffer.",
"x86", iError.ToString());
}
// Now that we know how much space we should reserve,
// we're going to reserve it and call
// GetLogicalProcessorInformation again.
uint iBaseSize = (uint)Marshal.SizeOf(
typeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx86));
uint iNumberOfElements = iReturnLength / iBaseSize;
SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx86[] oData =
new SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx86[iNumberOfElements];
uint iAllocatedSize = iNumberOfElements * iBaseSize;
if (!GetLogicalProcessorInformation(oData, ref iAllocatedSize))
{
throw Fail(
"GetLogicalProcessorInformation failed",
"x86",
Marshal.GetLastWin32Error().ToString());
}
// Converting the data to a list that we can easily interpret.
List<ProcessorInfo> oList = new List<ProcessorInfo>();
foreach (SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx86 oInfo in oData)
{
oList.Add(new ProcessorInfo(oInfo.Relationship,
oInfo.Flags,
oInfo.ProcessorMask));
}
return oList;
}
private static List<ProcessorInfo> GetProcessorInfo64()
{
// First we're going to execute GetLogicalProcessorInformation
// once to make sure that we determine the size of the data
// that it is going to return.
// This call should fail with error ERROR_INSUFFICIENT_BUFFER.
uint iReturnLength = 0;
SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx64[] oDummy = null;
bool bResult = GetLogicalProcessorInformation(oDummy,
ref iReturnLength);
if (bResult)
{
throw Fail("GetLogicalProcessorInformation failed.", "x64");
}
// Making sure that the error code that we got back is not
// that there is in sufficient space in the buffer.
int iError = Marshal.GetLastWin32Error();
if (iError != ERROR_INSUFFICIENT_BUFFER)
{
throw Fail(
"Insufficient space in the buffer.",
"x64", iError.ToString());
}
// Now that we know how much space we should reserve,
// we're going to reserve it and call
// GetLogicalProcessorInformation again.
uint iBaseSize = (uint)Marshal.SizeOf(
typeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx64));
uint iNumberOfElements = iReturnLength / iBaseSize;
SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx64[] oData =
new SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx64[iNumberOfElements];
uint iAllocatedSize = iNumberOfElements * iBaseSize;
if (!GetLogicalProcessorInformation(oData, ref iAllocatedSize))
{
throw Fail("GetLogicalProcessorInformation failed",
"x64", Marshal.GetLastWin32Error().ToString());
}
// Converting the data to a list that we can easily interpret.
List<ProcessorInfo> oList = new List<ProcessorInfo>();
foreach (SYSTEM_LOGICAL_PROCESSOR_INFORMATIONx64 oInfo in oData)
{
oList.Add(new ProcessorInfo(
oInfo.Relationship,
oInfo.Flags,
oInfo.ProcessorMask));
}
return oList;
}
private static Exception Fail(params string[] data)
{
return new NotSupportedException(
"GetPhysicalProcessorCount unexpectedly failed " +
"(" + String.Join(", ", data) + ")");
}
public static int GetPhysicalProcessorCount()
{
if (!Is64BitProcess)
{
Version oVersion = Environment.OSVersion.Version;
if (oVersion < new Version(5, 1, 2600))
{
throw new NotSupportedException(
"GetPhysicalProcessorCount is not supported " +
"on this operating system.");
}
else if (oVersion.Major == 5 &&
oVersion.Minor == 1 &&
!Environment.OSVersion.ServicePack.Equals(
"Service Pack 3",
StringComparison.OrdinalIgnoreCase))
{
throw new NotSupportedException(
"GetPhysicalProcessorCount is not supported " +
"on this operating system.");
}
}
// Getting a list of processor information
List<ProcessorInfo> oList;
if (Is64BitProcess)
{
oList = GetProcessorInfo64();
}
else
{
oList = GetProcessorInfo86();
}
// The list will basically contain something like this at this point:
//
// E.g. for a 2 x single core
// Relationship Flags ProcessorMask
// ---------------------------------------------------------
// RelationProcessorCore 0 1
// RelationProcessorCore 0 2
// RelationNumaNode 0 3
//
// E.g. for a 2 x dual core
// Relationship Flags ProcessorMask
// ---------------------------------------------------------
// RelationProcessorCore 1 5
// RelationProcessorCore 1 10
// RelationNumaNode 0 15
//
// E.g. for a 1 x quad core
// Relationship Flags ProcessorMask
// ---------------------------------------------------------
// RelationProcessorCore 1 15
// RelationNumaNode 0 15
//
// E.g. for a 1 x dual core
// Relationship Flags ProcessorMask
// ---------------------------------------------------------
// RelationProcessorCore 0 1
// RelationCache 1 1
// RelationCache 1 1
// RelationProcessorPackage 0 3
// RelationProcessorCore 0 2
// RelationCache 1 2
// RelationCache 1 2
// RelationCache 2 3
// RelationNumaNode 0 3
//
// Vista or higher will return one RelationProcessorPackage
// line per socket. On other operating systems we need to
// interpret the RelationProcessorCore lines.
//
// More information:
// http://msdn2.microsoft.com/en-us/library/ms683194(VS.85).aspx
// http://msdn2.microsoft.com/en-us/library/ms686694(VS.85).aspx
// First counting the number of RelationProcessorPackage lines
int iCount = 0;
foreach (ProcessorInfo oItem in oList)
{
if (oItem.Relationship ==
RelationProcessorCore.RelationProcessorPackage)
{
iCount++;
}
}
if (iCount > 0)
{
return iCount;
}
// Now we're going to use the information in RelationProcessorCore.
iCount = 0;
foreach (ProcessorInfo oItem in oList)
{
if (oItem.Relationship ==
RelationProcessorCore.RelationProcessorCore)
{
iCount++;
}
}
if (iCount > 0)
{
return iCount;
}
throw Fail("No cpus have been detected.");
}
}
}
|
And this is how you can use it:
| C# |
1
2
3
4
5
6
7
8
|
Console.WriteLine("64-bit Windows: " + Machine.Is64BitWindows);
Console.WriteLine("64-bit Process: " + Machine.Is64BitProcess);
Console.WriteLine("32-bit Process on a 64-bit Windows: " +
Machine.IsWow64Process);
Console.WriteLine("Number of physical CPU's: " +
Machine.GetPhysicalProcessorCount());
Console.WriteLine("Number of logical CPU's: " +
System.Environment.ProcessorCount);
|
The Is64BitWindows property returns true if this is a 64-bit
Windows, even while running on a 32-bit process. Is64BitProcess property
only returns true if this is a 64-bit process on a 64-bit Windows. The
IsWow64Process property returns true if this is a 32-bit process on a
64-bit Windows. Finally, the GetPhysicalProcessorCount function simply
returns the number of physical cpu's (sockets so to speak) on this server.
Many thanks to Nico Vuyge for providing us with the initial 32-bit version!