-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumCPULib.pas
1262 lines (1114 loc) · 35.2 KB
/
NumCPULib.pas
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{ *********************************************************************************** }
{ * NumCPULib Library * }
{ * Copyright (c) 2019 Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit NumCPULib;
{$DEFINE DELPHI}
{$IFDEF FPC}
{$UNDEF DELPHI}
{$MODE DELPHI}
// Disable Hints.
{$HINTS OFF}
{$IFDEF CPU386}
{$DEFINE NUMCPULIB_X86}
{$ENDIF}
{$IFDEF CPUX64}
{$DEFINE NUMCPULIB_X86_64}
{$ENDIF}
{$IFDEF CPUARM}
{$DEFINE NUMCPULIB_ARM}
{$ENDIF}
{$IFDEF CPUAARCH64}
{$DEFINE NUMCPULIB_AARCH64}
{$ENDIF}
{$IF DEFINED(NUMCPULIB_ARM) OR DEFINED(NUMCPULIB_AARCH64)}
{$DEFINE NUMCPULIB_ARMCPU}
{$IFEND}
{$IFDEF IPHONESIM}
{$DEFINE NUMCPULIB_IOSSIM}
{$ENDIF}
{$IF DEFINED(MSWINDOWS)}
{$DEFINE NUMCPULIB_MSWINDOWS}
{$ELSEIF DEFINED(UNIX)}
{$DEFINE NUMCPULIB_UNIX}
{$IF DEFINED(BSD)}
{$IF DEFINED(DARWIN)}
{$DEFINE NUMCPULIB_APPLE}
{$IF DEFINED(NUMCPULIB_ARM) OR DEFINED(NUMCPULIB_AARCH64)}
{$DEFINE NUMCPULIB_IOS}
{$ELSE}
{$DEFINE NUMCPULIB_MACOS}
{$IFEND}
{$ELSEIF DEFINED(FREEBSD) OR DEFINED(NETBSD) OR DEFINED(OPENBSD) OR DEFINED(DRAGONFLY)}
{$DEFINE NUMCPULIB_GENERIC_BSD}
{$IFEND}
{$ELSEIF DEFINED(ANDROID)}
{$DEFINE NUMCPULIB_ANDROID}
{$ELSEIF DEFINED(LINUX)}
{$DEFINE NUMCPULIB_LINUX}
{$ELSEIF DEFINED(SOLARIS)}
{$DEFINE NUMCPULIB_SOLARIS}
{$ELSE}
{$DEFINE NUMCPULIB_UNDEFINED_UNIX_VARIANTS}
{$IFEND}
{$ELSE}
{$MESSAGE ERROR 'UNSUPPORTED TARGET.'}
{$IFEND}
{$IFDEF NUMCPULIB_ANDROID}
{$DEFINE NUMCPULIB_LINUX}
{$ENDIF}
{$IF DEFINED(NUMCPULIB_GENERIC_BSD) OR DEFINED(NUMCPULIB_APPLE)}
{$DEFINE NUMCPULIB_HAS_SYSCTL}
{$IFEND}
{$IF DEFINED(NUMCPULIB_LINUX) OR DEFINED(NUMCPULIB_GENERIC_BSD) OR DEFINED(NUMCPULIB_SOLARIS) OR DEFINED(NUMCPULIB_APPLE)}
{$DEFINE NUMCPULIB_HAS_SYSCONF}
{$IFEND}
{$IF DEFINED(NUMCPULIB_LINUX) OR DEFINED(NUMCPULIB_SOLARIS)}
{$DEFINE NUMCPULIB_WILL_PARSE_DATA}
{$IFEND}
{$ENDIF FPC}
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
{$IFDEF DELPHI}
// XE3 and Above
{$IF CompilerVersion >= 24.0}
{$DEFINE DELPHIXE3_UP}
{$LEGACYIFEND ON}
{$ZEROBASEDSTRINGS OFF}
{$IFEND}
{$IFDEF CPU386}
{$DEFINE NUMCPULIB_X86}
{$ENDIF}
{$IFDEF CPUX64}
{$DEFINE NUMCPULIB_X86_64}
{$ENDIF}
{$IFDEF CPUARM32}
{$DEFINE NUMCPULIB_ARM}
{$ENDIF}
{$IFDEF CPUARM64}
{$DEFINE NUMCPULIB_AARCH64}
{$ENDIF}
{$IF DEFINED(NUMCPULIB_ARM) OR DEFINED(NUMCPULIB_AARCH64)}
{$DEFINE NUMCPULIB_ARMCPU}
{$IFEND}
{$IFDEF IOS}
{$IFNDEF CPUARM}
{$DEFINE NUMCPULIB_IOSSIM}
{$ENDIF}
{$ENDIF}
{$IFDEF IOS}
{$DEFINE NUMCPULIB_IOS}
{$ENDIF}
{$IFDEF MSWINDOWS}
{$DEFINE NUMCPULIB_MSWINDOWS}
{$ENDIF}
{$IFDEF MACOS}
{$IFNDEF IOS}
{$DEFINE NUMCPULIB_MACOS}
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
{$DEFINE NUMCPULIB_ANDROID}
{$ENDIF}
{$IF DEFINED(NUMCPULIB_IOS) OR DEFINED(NUMCPULIB_MACOS)}
{$DEFINE NUMCPULIB_APPLE}
{$IFEND}
{$IF DEFINED(LINUX) OR DEFINED(NUMCPULIB_ANDROID)}
{$DEFINE NUMCPULIB_LINUX}
{$IFEND}
{$IF DEFINED(NUMCPULIB_APPLE)}
{$DEFINE NUMCPULIB_HAS_SYSCTL}
{$IFEND}
{$IF DEFINED(NUMCPULIB_LINUX) OR DEFINED(NUMCPULIB_APPLE)}
{$DEFINE NUMCPULIB_HAS_SYSCONF}
{$IFEND}
{$IF DEFINED(NUMCPULIB_MSWINDOWS)}
// XE2 and Above
{$IF CompilerVersion >= 23.0}
{$DEFINE DELPHIXE2_UP}
{$DEFINE HAS_GET_LOGICAL_PROCESSOR_INFORMATION_INBUILT}
{$IFEND}
{$IFEND}
{$IFDEF NUMCPULIB_LINUX}
{$DEFINE NUMCPULIB_WILL_PARSE_DATA}
{$ENDIF}
{$ENDIF DELPHI}
interface
uses
{$IFDEF NUMCPULIB_MSWINDOWS}
Windows,
{$ENDIF} // ENDIF NUMCPULIB_MSWINDOWS
// ================================================================//
{$IFDEF NUMCPULIB_HAS_SYSCONF}
{$IFDEF FPC}
unixtype,
{$ELSE}
Posix.Unistd,
{$ENDIF} // ENDIF FPC
{$ENDIF} // ENDIF NUMCPULIB_HAS_SYSCONF
// ================================================================//
{$IFDEF NUMCPULIB_HAS_SYSCTL}
{$IFDEF FPC}
sysctl,
{$ELSE}
Posix.SysTypes,
Posix.SysSysctl,
{$ENDIF} // ENDIF FPC
{$ENDIF} // ENDIF NUMCPULIB_HAS_SYSCTL
// ================================================================//
{$IFDEF NUMCPULIB_APPLE}
{$IFDEF NUMCPULIB_MACOS}
{$IFDEF FPC}
CocoaAll,
{$ELSE}
Macapi.AppKit,
{$ENDIF} // ENDIF FPC
{$ENDIF} // ENDIF NUMCPULIB_MACOS
{$ENDIF} // ENDIF NUMCPULIB_APPLE
// ================================================================//
{$IFDEF NUMCPULIB_WILL_PARSE_DATA}
{$IFDEF NUMCPULIB_SOLARIS}
Process,
{$ENDIF} // ENDIF NUMCPULIB_SOLARIS
Classes,
StrUtils,
{$ENDIF} // ENDIF NUMCPULIB_WILL_PARSE_DATA
// ================================================================//
SysUtils;
type
/// <summary>
/// <para>
/// A class with utilities to determine the number of CPUs available on
/// the current system.
/// </para>
/// <para>
/// This information can be used as a guide to how many tasks can be
/// run in parallel.
/// </para>
/// <para>
/// There are many properties of the system architecture that will
/// affect parallelism, for example memory access speeds (for all the
/// caches and RAM) and the physical architecture of the processor, so
/// the number of CPUs should be used as a rough guide only.
/// </para>
/// </summary>
TNumCPULib = class sealed(TObject)
strict private
// ================================================================//
{$IFDEF NUMCPULIB_HAS_SYSCONF}
class function GetAppropriateSysConfNumber(): Int32; static;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_HAS_SYSCTL}
{$IFDEF NUMCPULIB_APPLE}
class function GetCPUCountUsingSysCtlByName(const AName: String)
: UInt32; static;
{$ENDIF}
class function GetLogicalCPUCountUsingSysCtl(): UInt32; static;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_MSWINDOWS}
const
KERNEL32 = 'kernel32.dll';
{$IFNDEF HAS_GET_LOGICAL_PROCESSOR_INFORMATION_INBUILT}
type
TLogicalProcessorRelationship = (RelationProcessorCore = 0,
RelationNumaNode = 1, RelationCache = 2, RelationProcessorPackage = 3,
RelationGroup = 4, RelationAll = $FFFF);
TProcessorCacheType = (CacheUnified, CacheInstruction, CacheData,
CacheTrace);
TCacheDescriptor = record
Level: Byte;
Associativity: Byte;
LineSize: Word;
Size: DWORD;
pcType: TProcessorCacheType;
end;
PSystemLogicalProcessorInformation = ^TSystemLogicalProcessorInformation;
TSystemLogicalProcessorInformation = record
ProcessorMask: ULONG_PTR;
Relationship: TLogicalProcessorRelationship;
case Int32 of
0:
(Flags: Byte);
1:
(NodeNumber: DWORD);
2:
(Cache: TCacheDescriptor);
3:
(Reserved: array [0 .. 1] of ULONGLONG);
end;
KAffinity = NativeUInt;
TGroupAffinity = record
Mask: KAffinity;
Group: Word;
Reserved: array [0 .. 2] of Word;
end;
TProcessorRelationship = record
Flags: Byte;
Reserved: array [0 .. 20] of Byte;
GroupCount: Word;
GroupMask: array [0 .. 0] of TGroupAffinity;
end;
TNumaNodeRelationship = record
NodeNumber: DWORD;
Reserved: array [0 .. 19] of Byte;
GroupMask: TGroupAffinity;
end;
TCacheRelationship = record
Level: Byte;
Associativity: Byte;
LineSize: Word;
CacheSize: DWORD;
_Type: TProcessorCacheType;
Reserved: array [0 .. 19] of Byte;
GroupMask: TGroupAffinity;
end;
TProcessorGroupInfo = record
MaximumProcessorCount: Byte;
ActiveProcessorCount: Byte;
Reserved: array [0 .. 37] of Byte;
ActiveProcessorMask: KAffinity;
end;
TGroupRelationship = record
MaximumGroupCount: Word;
ActiveGroupCount: Word;
Reserved: array [0 .. 19] of Byte;
GroupInfo: array [0 .. 0] of TProcessorGroupInfo;
end;
PSystemLogicalProcessorInformationEx = ^
TSystemLogicalProcessorInformationEx;
TSystemLogicalProcessorInformationEx = record
Relationship: TLogicalProcessorRelationship;
Size: DWORD;
case Int32 of
0:
(Processor: TProcessorRelationship);
1:
(NumaNode: TNumaNodeRelationship);
2:
(Cache: TCacheRelationship);
3:
(Group: TGroupRelationship);
end;
{$ENDIF}
// ================================================================//
type
TGetLogicalProcessorInformation = function(Buffer:
{$IFNDEF HAS_GET_LOGICAL_PROCESSOR_INFORMATION_INBUILT}TNumCPULib.{$ENDIF}PSystemLogicalProcessorInformation; var ReturnLength: DWORD): BOOL; stdcall;
TGetLogicalProcessorInformationEx = function(RelationshipType
: TLogicalProcessorRelationship; Buffer:
{$IFNDEF HAS_GET_LOGICAL_PROCESSOR_INFORMATION_INBUILT}TNumCPULib.{$ENDIF}PSystemLogicalProcessorInformationEx; var ReturnLength: DWORD): BOOL; stdcall;
class var
FIsGetLogicalProcessorInformationAvailable,
FIsGetLogicalProcessorInformationAvailableEx: Boolean;
FGetLogicalProcessorInformation: TGetLogicalProcessorInformation;
FGetLogicalProcessorInformationEx: TGetLogicalProcessorInformationEx;
// ================================================================//
type
TProcessorInformation = record
LogicalProcessorCount: UInt32;
ProcessorCoreCount: UInt32;
end;
type
TProcessorInformationEx = record
LogicalProcessorCount: UInt32;
ProcessorCoreCount: UInt32;
end;
// ================================================================//
class function GetProcedureAddress(ModuleHandle: THandle;
const AProcedureName: String; var AFunctionFound: Boolean): Pointer; static;
class function IsGetLogicalProcessorInformationAvailable(): Boolean; static;
class function IsGetLogicalProcessorInformationExAvailable(): Boolean; static;
class function CountSetBits(ABitMask: NativeUInt): UInt32; static;
class function GetProcessorInfo(): TProcessorInformation; static;
class function GetProcessorInfoEx(): TProcessorInformationEx; static;
class function GetLogicalCPUCountWindows(): UInt32; static;
class function GetPhysicalCPUCountWindows(): UInt32; static;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_APPLE}
class function GetLogicalCPUCountApple(): UInt32; static;
class function GetPhysicalCPUCountApple(): UInt32; static;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_WILL_PARSE_DATA}
type
TNumCPULibStringArray = array of String;
class function SplitString(const AInputString: String; ADelimiter: Char)
: TNumCPULibStringArray; static;
class function ParseLastString(const AInputString: String): String; static;
class function ParseLastInt32(const AInputString: String; ADefault: Int32)
: Int32; static;
class function BeginsWith(const AInputString, ASubString: string;
AIgnoreCase: Boolean; AOffset: Int32 = 1): Boolean; static;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_LINUX}
type
TLogicalProcessor = record
private
var
ProcessorNumber, PhysicalProcessorNumber, PhysicalPackageNumber: UInt32;
public
class function Create(AProcessorNumber, APhysicalProcessorNumber,
APhysicalPackageNumber: UInt32): TLogicalProcessor; static;
end;
class procedure ReadFileContents(const AFilePath: String;
var AOutputParameters: TStringList); static;
class function GetLogicalCPUCountLinux(): UInt32; static;
class function GetPhysicalCPUCountLinux(): UInt32; static;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_SOLARIS}
class procedure ExecuteAndParseProcessOutput(const ACallingProcess: String;
AInputParameters: TStringList; var AOutputParameters: TStringList);
class function GetLogicalCPUCountSolaris(): UInt32; static;
class function GetPhysicalCPUCountSolaris(): UInt32; static;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_GENERIC_BSD}
class function GetLogicalCPUCountGenericBSD(): UInt32; static;
{$ENDIF}
// ================================================================//
class procedure Boot(); static;
class constructor NumCPULib();
public
/// <summary>
/// This function will get the number of logical cores. Sometimes this is
/// different from the number of physical cores.
/// </summary>
class function GetLogicalCPUCount(): UInt32; static;
/// <summary>
/// This function will get the number of physical cores.
/// </summary>
class function GetPhysicalCPUCount(): UInt32; static;
end;
{$IFDEF NUMCPULIB_HAS_SYSCONF}
{$IFDEF FPC}
function sysconf(i: cint): clong; cdecl; external 'c' name 'sysconf';
{$ENDIF}
{$ENDIF}
implementation
{ TNumCPULib }
class procedure TNumCPULib.Boot();
begin
{$IFDEF NUMCPULIB_MSWINDOWS}
FIsGetLogicalProcessorInformationAvailable :=
IsGetLogicalProcessorInformationAvailable();
FIsGetLogicalProcessorInformationAvailableEx :=
IsGetLogicalProcessorInformationExAvailable();
{$ENDIF}
end;
class constructor TNumCPULib.NumCPULib;
begin
TNumCPULib.Boot();
end;
// ================================================================//
{$IFDEF NUMCPULIB_HAS_SYSCONF}
class function TNumCPULib.GetAppropriateSysConfNumber(): Int32;
begin
// On ARM targets, processors could be turned off to save power So we
// use `_SC_NPROCESSORS_CONF` to get the real number.
// ****************************************************************//
// NUMCPULIB_LINUX
{$IFDEF NUMCPULIB_LINUX}
{$IFDEF NUMCPULIB_ARMCPU}
{$IFDEF NUMCPULIB_ANDROID}
Result := 96; // _SC_NPROCESSORS_CONF
{$ELSE}
// Devices like RPI
Result := 83; // _SC_NPROCESSORS_CONF
{$ENDIF}
{$ELSE}
// for non ARM Linux like CPU's
{$IFDEF NUMCPULIB_ANDROID}
Result := 97; // _SC_NPROCESSORS_ONLN
{$ELSE}
Result := 84; // _SC_NPROCESSORS_ONLN
{$ENDIF} // ENDIF NUMCPULIB_ANDROID
{$ENDIF} // ENDIF NUMCPULIB_ARMCPU
{$ENDIF} // ENDIF NUMCPULIB_LINUX
// ****************************************************************//
// NUMCPULIB_GENERIC_BSD
{$IFDEF NUMCPULIB_GENERIC_BSD}
{$IF DEFINED(FREEBSD) OR DEFINED(DRAGONFLY)}
Result := 58; // _SC_NPROCESSORS_ONLN
{$IFEND}
{$IFDEF OPENBSD}
Result := 503; // _SC_NPROCESSORS_ONLN
{$ENDIF}
{$IFDEF NETBSD}
Result := 1002; // _SC_NPROCESSORS_ONLN
{$ENDIF}
{$ENDIF} // ENDIF NUMCPULIB_GENERIC_BSD
// ****************************************************************//
// NUMCPULIB_SOLARIS
{$IFDEF NUMCPULIB_SOLARIS}
{$IFDEF NUMCPULIB_ARMCPU}
Result := 14; // _SC_NPROCESSORS_CONF
{$ELSE}
Result := 15; // _SC_NPROCESSORS_ONLN
{$ENDIF}
{$ENDIF} // ENDIF NUMCPULIB_SOLARIS
// ****************************************************************//
// NUMCPULIB_APPLE
{$IFDEF NUMCPULIB_APPLE}
{$IFDEF NUMCPULIB_ARMCPU}
Result := 57; // _SC_NPROCESSORS_CONF
{$ELSE}
Result := 58; // _SC_NPROCESSORS_ONLN
{$ENDIF}
{$ENDIF} // ENDIF NUMCPULIB_APPLE
end;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_HAS_SYSCTL}
{$IFDEF NUMCPULIB_APPLE}
class function TNumCPULib.GetCPUCountUsingSysCtlByName
(const AName: String): UInt32;
var
LLen: size_t;
begin
LLen := System.SizeOf(Result);
{$IFDEF FPC}
fpsysctlbyname(PChar(AName), @Result, @LLen, nil, 0);
{$ELSE}
SysCtlByName(PAnsiChar(AName), @Result, @LLen, nil, 0);
{$ENDIF}
end;
{$ENDIF}
class function TNumCPULib.GetLogicalCPUCountUsingSysCtl(): UInt32;
var
LMib: array [0 .. 1] of Int32;
LLen: size_t;
begin
LMib[0] := CTL_HW;
LMib[1] := HW_NCPU;
LLen := System.SizeOf(Result);
{$IFDEF FPC}
{$IF DEFINED(VER3_0_0) OR DEFINED(VER3_0_2)}
fpsysctl(PChar(@LMib), 2, @Result, @LLen, nil, 0);
{$ELSE}
fpsysctl(@LMib, 2, @Result, @LLen, nil, 0);
{$IFEND}
{$ELSE}
sysctl(@LMib, 2, @Result, @LLen, nil, 0);
{$ENDIF}
end;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_MSWINDOWS}
class function TNumCPULib.CountSetBits(ABitMask: NativeUInt): UInt32;
var
LShift, LIdx: UInt32;
LBitTest: NativeUInt;
begin
LShift := (System.SizeOf(NativeUInt) * 8) - 1;
Result := 0;
LBitTest := NativeUInt(1) shl LShift;
LIdx := 0;
while LIdx <= LShift do
begin
if (ABitMask and LBitTest) <> 0 then
begin
System.Inc(Result);
end;
LBitTest := LBitTest shr 1;
System.Inc(LIdx);
end;
end;
class function TNumCPULib.GetProcessorInfo(): TProcessorInformation;
var
LReturnLength: DWORD;
LProcInfo, LCurrentInfo: PSystemLogicalProcessorInformation;
begin
LReturnLength := 0;
Result := Default (TProcessorInformation);
FGetLogicalProcessorInformation(nil, LReturnLength);
if GetLastError <> ERROR_INSUFFICIENT_BUFFER then
begin
RaiseLastOSError;
end
else
begin
System.GetMem(LProcInfo, LReturnLength);
try
if not FGetLogicalProcessorInformation(LProcInfo, LReturnLength) then
begin
RaiseLastOSError;
end
else
begin
LCurrentInfo := LProcInfo;
while (NativeUInt(LCurrentInfo) - NativeUInt(LProcInfo)) <
LReturnLength do
begin
case LCurrentInfo.Relationship of
RelationProcessorCore:
begin
System.Inc(Result.ProcessorCoreCount);
Result.LogicalProcessorCount := Result.LogicalProcessorCount +
CountSetBits(LCurrentInfo.ProcessorMask);
end;
end;
LCurrentInfo := PSystemLogicalProcessorInformation
(NativeUInt(LCurrentInfo) +
System.SizeOf(TSystemLogicalProcessorInformation));
end;
end;
finally
System.FreeMem(LProcInfo);
end;
end;
end;
class function TNumCPULib.GetProcessorInfoEx: TProcessorInformationEx;
var
LReturnLength: DWORD;
LProcInfo, LCurrentInfo: PSystemLogicalProcessorInformationEx;
LIdx: Int32;
begin
LReturnLength := 0;
Result := Default (TProcessorInformationEx);
FGetLogicalProcessorInformationEx(RelationAll, nil, LReturnLength);
if GetLastError <> ERROR_INSUFFICIENT_BUFFER then
begin
RaiseLastOSError;
end
else
begin
System.GetMem(LProcInfo, LReturnLength);
try
if not FGetLogicalProcessorInformationEx(RelationAll, LProcInfo,
LReturnLength) then
begin
RaiseLastOSError;
end
else
begin
LCurrentInfo := LProcInfo;
while (NativeUInt(LCurrentInfo) - NativeUInt(LProcInfo)) <
LReturnLength do
begin
case LCurrentInfo.Relationship of
RelationProcessorCore:
begin
System.Inc(Result.ProcessorCoreCount);
for LIdx := 0 to System.Pred
(LCurrentInfo.Processor.GroupCount) do
begin
Result.LogicalProcessorCount := Result.LogicalProcessorCount +
CountSetBits(LCurrentInfo.Processor.GroupMask[LIdx].Mask);
end;
end;
end;
LCurrentInfo := PSystemLogicalProcessorInformationEx
(NativeUInt(LCurrentInfo) + LCurrentInfo.Size);
end;
end;
finally
System.FreeMem(LProcInfo);
end;
end;
end;
class function TNumCPULib.GetLogicalCPUCountWindows(): UInt32;
var
LIdx: Int32;
LProcessAffinityMask, LSystemAffinityMask: DWORD_PTR;
LMask: DWORD;
LSystemInfo: SYSTEM_INFO;
LProcInfo: TProcessorInformation;
LProcInfoEx: TProcessorInformationEx;
begin
if IsGetLogicalProcessorInformationExAvailable then
begin
LProcInfoEx := GetProcessorInfoEx;
Result := LProcInfoEx.LogicalProcessorCount;
Exit;
end;
if IsGetLogicalProcessorInformationAvailable then
begin
LProcInfo := GetProcessorInfo;
Result := LProcInfo.LogicalProcessorCount;
Exit;
end;
// fallback if non of the above are available
// returns total number of processors available to system including logical hyperthreaded processors
LProcessAffinityMask := 0;
LSystemAffinityMask := 0;
if GetProcessAffinityMask(GetCurrentProcess, LProcessAffinityMask,
LSystemAffinityMask) then
begin
Result := 0;
for LIdx := 0 to 31 do
begin
LMask := DWORD(1) shl LIdx;
if (LProcessAffinityMask and LMask) <> 0 then
begin
System.Inc(Result);
end;
end;
end
else
begin
// can't get the affinity mask so we just report the total number of processors
LSystemInfo := Default (SYSTEM_INFO);
GetSystemInfo(LSystemInfo);
Result := LSystemInfo.dwNumberOfProcessors;
end;
end;
class function TNumCPULib.GetPhysicalCPUCountWindows(): UInt32;
var
LProcInfo: TProcessorInformation;
LProcInfoEx: TProcessorInformationEx;
begin
Result := 0;
if IsGetLogicalProcessorInformationExAvailable then
begin
LProcInfoEx := GetProcessorInfoEx;
Result := LProcInfoEx.ProcessorCoreCount;
Exit;
end;
if IsGetLogicalProcessorInformationAvailable then
begin
LProcInfo := GetProcessorInfo;
Result := LProcInfo.ProcessorCoreCount;
Exit;
end;
end;
class function TNumCPULib.GetProcedureAddress(ModuleHandle: THandle;
const AProcedureName: String; var AFunctionFound: Boolean): Pointer;
begin
Result := GetProcAddress(ModuleHandle, PChar(AProcedureName));
if Result = Nil then
begin
AFunctionFound := False;
end;
end;
class function TNumCPULib.IsGetLogicalProcessorInformationAvailable(): Boolean;
var
ModuleHandle: THandle;
begin
Result := False;
ModuleHandle := SafeLoadLibrary(KERNEL32, SEM_FAILCRITICALERRORS);
if ModuleHandle <> 0 then
begin
Result := True;
FGetLogicalProcessorInformation := GetProcedureAddress(ModuleHandle,
'GetLogicalProcessorInformation', Result);
end;
end;
class function TNumCPULib.IsGetLogicalProcessorInformationExAvailable: Boolean;
var
ModuleHandle: THandle;
begin
Result := False;
ModuleHandle := SafeLoadLibrary(KERNEL32, SEM_FAILCRITICALERRORS);
if ModuleHandle <> 0 then
begin
Result := True;
FGetLogicalProcessorInformationEx := GetProcedureAddress(ModuleHandle,
'GetLogicalProcessorInformationEx', Result);
end;
end;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_APPLE}
class function TNumCPULib.GetLogicalCPUCountApple(): UInt32;
var
LTempRes: Int32;
begin
{$IF DEFINED(NUMCPULIB_MACOS)}
// >= (Mac OS X 10.4+)
if NSAppKitVersionNumber >= 824 then // NSAppKitVersionNumber10_4
begin
LTempRes := sysconf(GetAppropriateSysConfNumber());
end
else
begin
// fallback for when sysconf API is not available
LTempRes := Int32(GetLogicalCPUCountUsingSysCtl());
end;
{$ELSE}
LTempRes := sysconf(GetAppropriateSysConfNumber());
{$IFEND}
// final fallback if all above fails
if LTempRes < 1 then
begin
Result := GetCPUCountUsingSysCtlByName('hw.logicalcpu');
end
else
begin
Result := UInt32(LTempRes);
end;
end;
class function TNumCPULib.GetPhysicalCPUCountApple(): UInt32;
begin
Result := GetCPUCountUsingSysCtlByName('hw.physicalcpu');
end;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_WILL_PARSE_DATA}
class function TNumCPULib.SplitString(const AInputString: String;
ADelimiter: Char): TNumCPULibStringArray;
var
LPosStart, LPosDel, LSplitPoints, LIdx, LLowIndex, LHighIndex, LLength: Int32;
begin
Result := Nil;
if AInputString <> '' then
begin
{ Determine the length of the resulting array }
LLowIndex := 1;
LHighIndex := System.Length(AInputString);
LSplitPoints := 0;
for LIdx := LLowIndex to LHighIndex do
begin
if (ADelimiter = AInputString[LIdx]) then
begin
System.Inc(LSplitPoints);
end;
end;
System.SetLength(Result, LSplitPoints + 1);
{ Split the string and fill the resulting array }
LIdx := 0;
LLength := System.Length(ADelimiter);
LPosStart := 1;
LPosDel := System.Pos(ADelimiter, AInputString);
while LPosDel > 0 do
begin
Result[LIdx] := System.Copy(AInputString, LPosStart, LPosDel - LPosStart);
LPosStart := LPosDel + LLength;
LPosDel := PosEx(ADelimiter, AInputString, LPosStart);
System.Inc(LIdx);
end;
Result[LIdx] := System.Copy(AInputString, LPosStart,
System.Length(AInputString));
end;
end;
class function TNumCPULib.ParseLastString(const AInputString: String): String;
var
LSplitResult: TNumCPULibStringArray;
begin
LSplitResult := SplitString(AInputString, ' ');
if (System.Length(LSplitResult) < 1) then
begin
Result := Trim(AInputString);
end
else
begin
Result := Trim(LSplitResult[System.Length(LSplitResult) - 1]);
end;
end;
class function TNumCPULib.ParseLastInt32(const AInputString: String;
ADefault: Int32): Int32;
var
LLocalString: String;
begin
LLocalString := ParseLastString(AInputString);
if BeginsWith(LowerCase(LLocalString), '0x', False) then
begin
Result := StrToIntDef(StringReplace(LLocalString, '0x', '$',
[rfReplaceAll, rfIgnoreCase]), ADefault);
end
else
begin
Result := StrToIntDef(LLocalString, ADefault);
end;
end;
class function TNumCPULib.BeginsWith(const AInputString, ASubString: String;
AIgnoreCase: Boolean; AOffset: Int32): Boolean;
var
LIdx: Int32;
LPtrInputString, LPtrSubString: PChar;
begin
LIdx := System.Length(ASubString);
Result := LIdx > 0;
LPtrInputString := PChar(AInputString);
System.Inc(LPtrInputString, AOffset - 1);
LPtrSubString := PChar(ASubString);
if Result then
begin
if AIgnoreCase then
begin
Result := StrLiComp(LPtrSubString, LPtrInputString, LIdx) = 0
end
else
begin
Result := StrLComp(LPtrSubString, LPtrInputString, LIdx) = 0
end;
end;
end;
{$ENDIF}
// ================================================================//
{$IFDEF NUMCPULIB_LINUX}
class function TNumCPULib.TLogicalProcessor.Create(AProcessorNumber,
APhysicalProcessorNumber, APhysicalPackageNumber: UInt32): TLogicalProcessor;
begin
Result := Default (TLogicalProcessor);
Result.ProcessorNumber := AProcessorNumber;
Result.PhysicalProcessorNumber := APhysicalProcessorNumber;
Result.PhysicalPackageNumber := APhysicalPackageNumber;
end;
class procedure TNumCPULib.ReadFileContents(const AFilePath: String;
var AOutputParameters: TStringList);
const
BUF_SIZE = 2048; // Buffer size for reading the output in chunks
var
LOutputStream: TStream;
LFileStream: TFileStream;
LBytesRead: LongInt;
LBuffer: array [0 .. BUF_SIZE - 1] of Byte;
begin
if SysUtils.FileExists(AFilePath) then
begin
LFileStream := TFileStream.Create(AFilePath, fmOpenRead);
try
LOutputStream := TMemoryStream.Create;
try
// All data from file is read in a loop until no more data is available
repeat
// Get the new data from the file to a maximum of the LBuffer size that was allocated.
// Note that all read(...) calls will block except for the last one, which returns 0 (zero).
LBytesRead := LFileStream.Read(LBuffer, BUF_SIZE);
// Add the bytes that were read to the stream for later usage
LOutputStream.Write(LBuffer, LBytesRead)
until LBytesRead = 0; // Stop if no more data is available
// Required to make sure all data is copied from the start