-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCpuCount.cs
544 lines (506 loc) · 17.3 KB
/
CpuCount.cs
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
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.");
}
public static int GetPhysicalProcessorCores()
{
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
// Now we're going to use the information in RelationProcessorCore.
int 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.");
}
}
}