forked from spring4d/benchmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpring.Benchmark.pas
4930 lines (4262 loc) · 140 KB
/
Spring.Benchmark.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
{***************************************************************************}
{ }
{ Spring Benchmark for Delphi }
{ }
{ Copyright (c) 2021 Spring4D Team }
{ }
{ http://www.spring4d.org }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
// This is a port from Google Benchmark: https://github.com/google/benchmark - v1.5.3
unit Spring.Benchmark;
{$T-,X+,H+,B-}
{$IFNDEF DEBUG}{$O+,W-}{$ENDIF}
{$INLINE ON}
{$IFDEF FPC}
{$IFOPT D+}{$DEFINE DEBUG}{$ENDIF}
{$MODE DELPHI}
{$ASMMODE INTEL}
{$DEFINE HAS_RECORD_FINALIZER}
{$NOTES OFF}
{$HINTS OFF}
{$WARNINGS OFF}
{$ELSE}
{$LEGACYIFEND ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$DEFINE HAS_UNITSCOPE}
{$IF CompilerVersion < 28.0}
{$MESSAGE ERROR 'Delphi XE7 or higher required'}
{$IFEND}
{$IF CompilerVersion >= 34.0}
{$DEFINE HAS_RECORD_FINALIZER}
{$IFEND}
{$IFDEF ANDROID}
{$DEFINE APP_LOG}
{$DEFINE DELPHI_ANDROID}
{$ENDIF}
{$IFDEF IOS}
{$DEFINE APP_LOG}
{$DEFINE DELPHI_DARWIN}
{$ENDIF}
{$IFDEF OSX}
{$DEFINE APP_LOG}
{$DEFINE DELPHI_DARWIN}
{$ENDIF}
{$ENDIF}
interface
uses
{$IFDEF HAS_UNITSCOPE}
System.SyncObjs;
{$ELSE}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SyncObjs;
{$ENDIF}
type
{$IFDEF FPC}
{$IFDEF MSWINDOWS}
TRTLConditionVariable = record
Ptr: Pointer;
end;
{$ENDIF}
{$IFDEF UNIX}
TRTLConditionVariable = pthread_cond_t;
{$ENDIF}
TConditionVariable = class
private
fConditionVariable: TRTLConditionVariable;
public
procedure ReleaseAll;
procedure WaitFor(criticalSection: TCriticalSection);
end;
{$ELSE}
{$IFDEF MSWINDOWS}
TConditionVariable = TConditionVariableCS;
{$ELSE}
TConditionVariable = TConditionVariableMutex;
TCriticalSection = TMutex;
{$ENDIF}
{$ENDIF}
PCounter = ^TCounter;
TCounter = record
type
TFlag = (
// Mark the counter as a rate. It will be presented divided
// by the duration of the benchmark.
kIsRate,
// Mark the counter as a thread-average quantity. It will be
// presented divided by the number of threads.
kAvgThreads,
// Mark the counter as a constant value, valid/same for *every* iteration.
// When reporting, it will be *multiplied* by the iteration count.
kIsIterationInvariant,
// Mark the counter as a iteration-average quantity.
// It will be presented divided by the number of iterations.
kAvgIterations,
// In the end, invert the result. This is always done last!
kInvert
);
TFlags = set of TFlag;
type
TOneK = (
// 1'000 items per 1k
kIs1000,
// 1'024 items per 1k
kIs1024
);
public
value: Double;
flags: TFlags;
oneK: TOneK;
procedure Init(v: Double = 0.0; f: TFlags = []; k: TOneK = kIs1000); inline;
class operator Implicit(const value: Double): TCounter;
end;
const
// Mark the counter as a thread-average rate. See above.
kAvgThreadsRate = [kIsRate, kAvgThreads];
// Mark the counter as a constant rate.
// When reporting, it will be *multiplied* by the iteration count
// and then divided by the duration of the benchmark.
kIsIterationInvariantRate = [kIsRate, kIsIterationInvariant];
// Mark the counter as a iteration-average rate. See above.
kAvgIterationsRate = [kIsRate, kAvgIterations];
type
TUserCounter = record name: string; counter: TCounter end;
TUserCounters = array of TUserCounter;
TUserCountersHelper = record helper for TUserCounters
function Find(const name: string): PCounter;
function Get(const name: string): PCounter;
end;
PCounterStat = ^TCounterStat;
TCounterStat = record c: TCounter; s: TArray<Double>; end;
TCounterStatsItem = record name: string; counter: TCounterStat end;
TCounterStats = array of TCounterStatsItem;
TCounterStatsHelper = record helper for TCounterStats
function Find(const name: string): PCounterStat;
function Get(const name: string): PCounterStat;
end;
TBigO = (oNone, o1, oN, oNSquared, oNCubed, oLogN, oNLogN, oAuto, oLambda);
TIterationCount = type UInt64;
TBigOFunc = {$IFNDEF FPC}reference to{$ENDIF} function(const n: TIterationCount): Double;
TStatisticsFunc = {$IFNDEF FPC}reference to{$ENDIF} function(const values: array of Double): Double;
TStatistics = record
Name: string;
Compute: TStatisticsFunc;
constructor Create(const name: string; const compute: TStatisticsFunc);
end;
TThreadTimer = class
strict private
// should the thread, or the process, time be measured?
fMeasureProcessCpuTime: Boolean;
fRunning: Boolean;
fStartRealTime,
fStartCpuTime,
// Accumulated time so far (does not contain current slice if running)
fRealTimeUsed,
fCpuTimeUsed,
// Manually set iteration time. User sets this with SetIterationTime(seconds).
fManualTimeUsed: Double;
function GetRealTimeRunning: Double; inline;
function GetCpuTimeUsed: Double; inline;
function GetManualTimeUsed: Double; inline;
function ReadCpuTimerOfChoice: Double;
private
constructor Create(measureProcessCpuTime: Boolean);
public
constructor CreateProcessCpuTime;
// Called by each thread
procedure StartTimer;
// Called by each thread
procedure StopTimer;
// Called by each thread
procedure SetIterationTime(seconds: Double);
property Running: Boolean read fRunning;
// REQUIRES: timer is not running
property RealTimeUsed: Double read GetRealTimeRunning;
// REQUIRES: timer is not running
property CpuTimeUsed: Double read GetCpuTimeUsed;
// REQUIRES: timer is not running
property ManualTimeUsed: Double read GetManualTimeUsed;
end;
TBarrier = class
private
fLock: TCriticalSection;
fPhaseCondition: TConditionVariable;
fRunningThreads: Integer;
fPhaseNumber: Integer;
fEntered: Integer;
function CreateBarrier: Boolean;
public
constructor Create(numThreads: Integer);
destructor Destroy; override;
function Wait: Boolean;
procedure RemoveThread;
end;
TThreadManager = class
type
TResult = record
iterations: TIterationCount;
realTimeUsed: Double;
cpuTimeUsed: Double;
manualTimeUsed: Double;
complexityN: UInt64;
reportLabel: string;
errorMessage: string;
hasError: Boolean;
counters: TUserCounters;
end;
private
fBenchmarkLock: TCriticalSection;
fAliveThreads: Integer;
fStartStopBarrier: TBarrier;
fEndCondLock: TCriticalSection;
fEndCondition: TConditionVariable;
public
results: TResult;
constructor Create(const numThreads: Integer);
destructor Destroy; override;
procedure Lock;
procedure Unlock;
function StartStopBarrier: Boolean; inline;
procedure NotifyThreadComplete;
procedure WaitForAllThreads;
end;
TAggregationReportMode = (
// The mode is user-specified.
// This may or may not be set when the following bit-flags are set.
armDefault,
// File reporter should only output aggregates.
armFileReportAggregatesOnly,
// Display reporter should only output aggregates
armDisplayReportAggregatesOnly
);
TAggregationReportModes = set of TAggregationReportMode;
const
armUnspecified = [];
// Both reporters should only display aggregates.
armReportAggregatesOnly = [armFileReportAggregatesOnly, armDisplayReportAggregatesOnly];
type
// State is passed to a running Benchmark and contains state for the
// benchmark to use.
TState = record
type
TValue = record end;
TStateIterator = record
private
fCached: TIterationCount;
fParent: ^TState;
fCurrent: TValue;
public
function MoveNext: Boolean; inline;
{$IFDEF HAS_RECORD_FINALIZER}
{$IFDEF FPC}
class operator Initialize(var iter: TStateIterator);
{$ENDIF}
class operator Finalize(var iter: TStateIterator);
{$ENDIF}
property Current: TValue read fCurrent;
end;
strict private
// When total_iterations_ is 0, KeepRunning() and friends will return false.
// May be larger than max_iterations.
fTotalIterations,
// When using KeepRunningBatch(), batch_leftover_ holds the number of
// iterations beyond max_iters that were run. Used to track
// completed_iterations_ accurately.
fBatchLeftover,
fMaxIterations: TIterationCount;
fStarted, fFinished, fErrorOccurred: Boolean;
fRange: TArray<Int64>;
fComplexityN: UInt64;
fTimer: TThreadTimer;
fManager: TThreadManager;
fThreadIndex: Integer;
fThreads: Integer;
function GetBytesProcessed: UInt64;
function GetItemsProcessed: UInt64;
function GetIterations: TIterationCount;
function GetRange(index: Integer): Int64; inline;
function GetCounter(const name: string): TCounter;
procedure SetCounter(const name: string; const value: TCounter);
procedure StartKeepRunning;
// Implementation of KeepRunning() and KeepRunningBatch().
// isBatch must be true unless n is 1.
function KeepRunningInternal(const n: TIterationCount; isBatch: Boolean): Boolean; inline;
procedure FinishKeepRunning; {$IFDEF HAS_RECORD_FINALIZER}inline;{$ENDIF}
private
// Container for user-defined counters.
fCounters: TUserCounters;
constructor Create(const maxIters: TIterationCount; const ranges: TArray<Int64>;
threadId, threadCount: Integer; const timer: TThreadTimer;
const manager: TThreadManager);
property MaxIterations: TIterationCount read fMaxIterations;
public
// Index of the executing thread. Values from [0, threads).
property ThreadIndex: Integer read fThreadIndex;
// Number of threads concurrently executing the benchmark.
property Threads: Integer read fThreads;
// Returns iterator used to run each iteration of a benchmark using a
// for-in loop. This function should not be called directly.
//
// REQUIRES: The benchmark has not started running yet. Neither begin nor end
// have been called previously.
//
// NOTE: KeepRunning may not be used after calling either of these functions.
function GetEnumerator: TStateIterator; inline;
// Returns true if the benchmark should continue through another iteration.
// NOTE: A benchmark may not return from the test until KeepRunning() has
// returned false.
function KeepRunning: Boolean; inline;
// Returns true if the benchmark should run n more iterations.
// REQUIRES: 'n' > 0.
// NOTE: A benchmark must not return from the test until KeepRunningBatch()
// has returned false.
// NOTE: KeepRunningBatch() may overshoot by up to 'n' iterations.
//
// Intended usage:
// while state.KeepRunningBatch(1000) do
// // process 1000 elements
function KeepRunningBatch(const n: TIterationCount): Boolean; inline;
// REQUIRES: timer is running and 'SkipWithError(...)' has not been called
// by the current thread.
// Stop the benchmark timer. If not called, the timer will be
// automatically stopped after the last iteration of the benchmark loop.
//
// For threaded benchmarks the PauseTiming() function only pauses the timing
// for the current thread.
//
// NOTE: The "real time" measurement is per-thread. If different threads
// report different measurements the largest one is reported.
//
// NOTE: PauseTiming()/ResumeTiming() are relatively
// heavyweight, and so their use should generally be avoided
// within each benchmark iteration, if possible.
procedure PauseTiming; inline;
// REQUIRES: timer is not running and 'SkipWithError(...)' has not been called
// by the current thread.
// Start the benchmark timer. The timer is NOT running on entrance to the
// benchmark function. It begins running after control flow enters the
// benchmark loop.
//
// NOTE: PauseTiming()/ResumeTiming() are relatively
// heavyweight, and so their use should generally be avoided
// within each benchmark iteration, if possible.
procedure ResumeTiming; inline;
// REQUIRES: 'SkipWithError(...)' has not been called previously by the
// current thread.
// Report the benchmark as resulting in an error with the specified 'msg'.
// After this call the user may explicitly 'return' from the benchmark.
//
// If the ranged-for style of benchmark loop is used, the user must explicitly
// break from the loop, otherwise all future iterations will be run.
// If the 'KeepRunning()' loop is used the current thread will automatically
// exit the loop at the end of the current iteration.
//
// For threaded benchmarks only the current thread stops executing and future
// calls to `KeepRunning()` will block until all threads have completed
// the `KeepRunning()` loop. If multiple threads report an error only the
// first error message is used.
//
// NOTE: Calling 'SkipWithError(...)' does not cause the benchmark to exit
// the current scope immediately. If the function is called from within
// the 'KeepRunning()' loop the current iteration will finish. It is the users
// responsibility to exit the scope as needed.
procedure SkipWithError(const msg: string);
// Returns true if an error has been reported with 'SkipWithError(...)'.
property ErrorOccurred: Boolean read fErrorOccurred;
// REQUIRES: called exactly once per iteration of the benchmarking loop.
// Set the manually measured time for this benchmark iteration, which
// is used instead of automatically measured time if UseManualTime() was
// specified.
//
// For threaded benchmarks the final value will be set to the largest
// reported values.
procedure SetIterationTime(const seconds: Double);
// Set the number of bytes processed by the current benchmark
// execution. This routine is typically called once at the end of a
// throughput oriented benchmark.
//
// REQUIRES: a benchmark has exited its benchmarking loop.
procedure SetBytesProcessed(const bytes: UInt64);
// If this routine is called with complexityN > 0 and complexity report is
// requested for the
// family benchmark, then current benchmark will be part of the computation
// and complexityN will
// represent the length of N.
procedure SetComplexityN(const complexityN: UInt64); inline;
// If this routine is called with items > 0, then an items/s
// label is printed on the benchmark report line for the currently
// executing benchmark. It is typically called at the end of a processing
// benchmark where a processing items/second output is desired.
//
// REQUIRES: a benchmark has exited its benchmarking loop.
procedure SetItemsProcessed(const items: UInt64);
// If this routine is called, the specified label is printed at the
// end of the benchmark report line for the currently executing
// benchmark. Example:
// procedure BM_Compress(const state: TState);
// begin
// ...
// var compress = input_size / output_size;
// state.SetLabel(Format('compress:%.1f%%', 100.0 * compression));
// end;
// Produces output that looks like:
// BM_Compress 50 50 14115038 compress:27.3%
//
// REQUIRES: a benchmark has exited its benchmarking loop.
procedure SetLabel(const text: string);
property BytesProcessed: UInt64 read GetBytesProcessed;
property ComplexityN: UInt64 read fComplexityN;
property ItemsProcessed: UInt64 read GetItemsProcessed;
property Iterations: TIterationCount read GetIterations;
property Counters[const name: string]: TCounter read GetCounter write SetCounter;
// Range arguments for this run. CHECKs if the argument has been set.
property Range[index: Integer]: Int64 read GetRange; default;
end;
TFunction = procedure(const state: TState);
TTimeUnit = (kNanosecond, kMicrosecond, kMillisecond, kSecond);
// ------------------------------------------------------
// Benchmark registration object. The Benchmark() function returns this.
// Various methods can be called on this object to change the properties of
// the benchmark. Each method returns "this" so that multiple method calls
// can chained into one expression.
TBenchmark = class
type
TRange = record start, limit: Int64 end;
TCustomizeFunc = {$IFNDEF FPC}reference to{$ENDIF} procedure(const benchmark: TBenchmark);
private
fName: string;
fAggregationReportMode: TAggregationReportModes;
fArgNames: TArray<string>;
fArgs: TArray<TArray<Int64>>;
fTimeUnit: TTimeUnit;
fRangeMultiplier: Integer;
fMinTime: Double;
fIterations: TIterationCount;
fRepetitions: Integer;
fMeasureProcessCpuTime,
fUseRealTime,
fUseManualTime: Boolean;
fComplexity: TBigO;
fComplexityLambda: TBigOFunc;
fStatistics: TArray<TStatistics>;
fThreadCounts: TArray<Integer>;
function GetArgsCount: Integer;
strict protected
constructor Create(const name: string);
public
procedure Run(const state: TState); virtual; abstract;
// Note: the following methods all return "Self" so that multiple
// method calls can be chained together in one expression.
// Run this benchmark once with "x" as the extra argument passed
// to the function.
// REQUIRES: The function passed to the constructor must accept an arg1.
function Arg(const x: Int64): TBenchmark;
// Run this benchmark with the given time unit for the generated output report
function TimeUnit(const timeUnit: TTimeUnit): TBenchmark;
// Run this benchmark once for a number of values picked from the
// range [start..limit]. (start and limit are always picked.)
// REQUIRES: The function passed to the constructor must accept an arg1.
function Range(const start, limit: Int64): TBenchmark;
// Run this benchmark once for all values in the range [start..limit] with
// specific step
// REQUIRES: The function passed to the constructor must accept an arg1.
function DenseRange(const start, limit: Int64; step: Integer = 1): TBenchmark;
// Run this benchmark once with "args" as the extra arguments passed
// to the function.
// REQUIRES: The function passed to the constructor must accept arg1, arg2 ...
function Args(const args: array of Int64): TBenchmark;
// Run this benchmark once for a number of values picked from the
// ranges [start..limit]. (starts and limits are always picked.)
// REQUIRES: The function passed to the constructor must accept arg1, arg2 ...
function Ranges(const ranges: array of TRange): TBenchmark;
// Run this benchmark once for each combination of values in the (cartesian)
// product of the supplied argument lists.
// REQUIRES: The function passed to the constructor must accept arg1, arg2 ...
function ArgsProduct(const argLists: TArray<TArray<Int64>>): TBenchmark;
// Equivalent to ArgNames([name])
function ArgName(const name: string): TBenchmark;
// Set the argument names to display in the benchmark name. If not called,
// only argument values will be shown.
function ArgNames(const names: array of string): TBenchmark;
// Pass this benchmark object to customArguments, which can customize
// the benchmark by calling various methods like Arg, Args,
// Threads, etc.
function Apply(const customArguments: TCustomizeFunc): TBenchmark;
// Set the range multiplier for non-dense range. If not called, the range
// multiplier kRangeMultiplier will be used.
function RangeMultiplier(const multiplier: Integer): TBenchmark;
// Set the minimum amount of time to use when running this benchmark. This
// option overrides the `benchmark_min_time` flag.
// REQUIRES: `t > 0` and `Iterations` has not been called on this benchmark.
function MinTime(const t: Double): TBenchmark;
// Specify the amount of iterations that should be run by this benchmark.
// REQUIRES: 'n > 0' and `MinTime` has not been called on this benchmark.
//
// NOTE: This function should only be used when *exact* iteration control is
// needed and never to control or limit how long a benchmark runs, where
// `--benchmark_min_time=N` or `MinTime(...)` should be used instead.
function Iterations(const n: TIterationCount): TBenchmark;
// Specify the amount of times to repeat this benchmark. This option overrides
// the `benchmark_repetitions` flag.
// REQUIRES: `n > 0`
function Repetitions(const n: Integer): TBenchmark;
// Specify if each repetition of the benchmark should be reported separately
// or if only the final statistics should be reported. If the benchmark
// is not repeated then the single result is always reported.
// Applies to *ALL* reporters (display and file).
function ReportAggregatesOnly(const value: Boolean = True): TBenchmark;
// Same as ReportAggregatesOnly(), but applies to display reporter only.
function DisplayAggregatesOnly(const value: Boolean = True): TBenchmark;
// By default, the CPU time is measured only for the main thread, which may
// be unrepresentative if the benchmark uses threads internally. If called,
// the total CPU time spent by all the threads will be measured instead.
// By default, the only the main thread CPU time will be measured.
function MeasureProcessCPUTime: TBenchmark;
// If a particular benchmark should use the Wall clock instead of the CPU time
// (be it either the CPU time of the main thread only (default), or the
// total CPU usage of the benchmark), call this method. If called, the elapsed
// (wall) time will be used to control how many iterations are run, and in the
// printing of items/second or MB/seconds values.
// If not called, the CPU time used by the benchmark will be used.
function UseRealTime: TBenchmark;
// If a benchmark must measure time manually (e.g. if GPU execution time is
// being
// measured), call this method. If called, each benchmark iteration should
// call
// SetIterationTime(seconds) to report the measured time, which will be used
// to control how many iterations are run, and in the printing of items/second
// or MB/second values.
function UseManualTime: TBenchmark;
// Set the asymptotic computational complexity for the benchmark. If called
// the asymptotic computational complexity will be shown on the output.
function Complexity(const complexity: TBigO = oAuto): TBenchmark; overload;
// Set the asymptotic computational complexity for the benchmark. If called
// the asymptotic computational complexity will be shown on the output.
function Complexity(const complexity: TBigOFunc): TBenchmark; overload;
// Add this statistics to be computed over all the values of benchmark run
function ComputeStatistics(const name: string; const statistics: TStatisticsFunc): TBenchmark;
// Support for running multiple copies of the same benchmark concurrently
// in multiple threads. This may be useful when measuring the scaling
// of some piece of code.
// Run one instance of this benchmark concurrently in t threads.
function Threads(const t: Integer): TBenchmark;
property ArgsCount: Integer read GetArgsCount;
end;
procedure Benchmark_Main(pinThread0: Boolean = False);
function Benchmark(const fn: TFunction; const name: string): TBenchmark;
function Range(const start, limit: Int64): TBenchmark.TRange;
function Counter(const value: Double; flags: TCounter.TFlags = []; k: TCounter.TOneK = kIs1000): TCounter; inline;
{$REGION 'Global settings'}
// The following variables are being set via commandline parameters
// but can also be set in code.
var
// Print a list of benchmarks. This option overrides all other options.
benchmark_list_tests: Boolean = False;
// A regular expression that specifies the set of benchmarks to execute. If
// this flag is empty, or if this flag is the string \"all\", all benchmarks
// linked into the binary are run.
benchmark_filter: string = '.';
// Minimum number of seconds we should run benchmark before results are
// considered significant. For cpu-time based tests, this is the lower bound
// on the total cpu time used by all threads that make up the test. For
// real-time based tests, this is the lower bound on the elapsed time of the
// benchmark execution, regardless of number of threads.
benchmark_min_time: Double = 0.5;
// The number of runs of each benchmark. If greater than 1, the mean and
// standard deviation of the runs will be reported.
benchmark_repetitions: Integer = 1;
// Report the result of each benchmark repetitions. When 'true' is specified
// only the mean, standard deviation, and other statistics are reported for
// repeated benchmarks. Affects all reporters.
benchmark_report_aggregates_only: Boolean = False;
// Display the result of each benchmark repetitions. When 'true' is specified
// only the mean, standard deviation, and other statistics are displayed for
// repeated benchmarks. Unlike benchmark_report_aggregates_only, only affects
// the display reporter, but *NOT* file reporter, which will still contain
// all the output.
benchmark_display_aggregates_only: Boolean = False;
// The format to use for console output.
// Valid values are 'console', 'json', or 'csv'.
benchmark_format: string = 'console';
// The format to use for file output.
// Valid values are 'console', 'json', or 'csv'.
benchmark_out_format: string = 'json';
// The file to write additional output to.
benchmark_out: string = '';
// Whether to use colors in the output. Valid values:
// 'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use colors if
// the output is being sent to a terminal and the TERM environment variable is
// set to a terminal type that supports colors.
benchmark_color: string = 'auto';
// Whether to use tabular format when printing user counters to the console.
// Valid values: 'true'/'yes'/1, 'false'/'no'/0. Defaults to false.
benchmark_counters_tabular: Boolean = False;
// Whether to add formatted args to the output.
// Valid values: 'true'/'yes'/1, 'false'/'no'/0. Defaults to true.
benchmark_format_args: Boolean = True;
// The level of verbose logging to output
log_level: Integer = 0;
// separator used for the csv file
csv_separator: Char = ';';
{$ENDREGION}
implementation
uses
{$IFDEF HAS_UNITSCOPE}
{$IFDEF MSWINDOWS}
Winapi.ShLwApi,
Winapi.Windows,
{$ELSE}
Posix.Base,
Posix.Stdlib,
Posix.SysTime,
Posix.Time,
Posix.Unistd,
Posix.Fcntl,
Posix.SysSysctl,
Posix.StdDef,
{$IFDEF ANDROID}
Androidapi.JNI.JavaTypes,
Androidapi.Helpers,
Androidapi.Log,
{$ENDIF}
{$IFDEF IOS}
Macapi.Mach,
Macapi.Helpers,
Macapi.ObjectiveC,
iOSapi.Foundation,
{$ENDIF}
{$IFDEF OSX}
Macapi.Mach,
Macapi.Helpers,
Macapi.ObjectiveC,
Macapi.Foundation,
{$ENDIF}
{$ENDIF}
System.Classes,
System.Character,
System.DateUtils,
System.Math,
System.RegularExpressions,
System.StrUtils,
System.SysUtils;
{$ELSE}
Classes,
Character,
DateUtils,
Math,
RegExpr,
StrUtils,
SysUtils;
{$ENDIF}
type
TCPUInfo = record
type
TCacheInfo = record
typ: string;
level: Cardinal;
size: Cardinal;
numSharing: Integer;
end;
TScaling = (Unknown, Enabled, Disabled);
public class var
numCpus: Integer;
cyclesPerSecond: Double;
cycleDuration: Double;
caches: TArray<TCacheInfo>;
scaling: TScaling;
loadAvg: TArray<Double>;
class constructor Create;
end;
TFunctionBenchmark = class(TBenchmark)
strict private
fFunc: TFunction;
public
constructor Create(const name: string; const func: TFunction);
procedure Run(const state: TState); override;
end;
TBenchmarkName = record
functionName: string;
args: string;
minTime: string;
iterations: string;
pepetitions: string;
timeType: string;
threads: string;
function Str: string;
end;
TBenchmarkInstance = record
name: TBenchmarkName;
benchmark: TBenchmark;
aggregationReportMode: TAggregationReportModes;
arg: TArray<Int64>;
timeUnit: TTimeUnit;
rangeMultiplier: Integer;
measureProcessCpuTime,
useRealTime,
useManualTime: Boolean;
complexity: TBigO;
complexityLambda: TBigOFunc;
counters: TUserCounters;
statistics: TArray<TStatistics>;
lastBenchmarkInstance: Boolean;
repetitions: Integer;
minTime: Double;
iterations: TIterationCount;
threads: Cardinal;
function Run(const iters: TIterationCount; threadId: Integer;
const timer: TThreadTimer; const manager: TThreadManager): TState;
end;
TBenchmarkFamilies = class
strict private class var
fFamilies: TList;
fLock: TCriticalSection;
class constructor Create;
class destructor Destroy;
public
class function AddBenchmark(const family: TBenchmark): Integer;
class procedure ClearBenchmarks;
class function FindBenchmarks(spec: string;
var benchmarks: TArray<TBenchmarkInstance>): Boolean;
end;
TBenchmarkReporter = class
type
TContext = record
// The number of chars in the longest benchmark name.
nameFieldWidth: NativeUInt;
class var executableName: string;
end;
TRun = record
const noRepetitionIndex = -1;
type TRunType = (rtIteration, rtAggregate);
strict private
function GetBenchmarkName: string;
public
runName: TBenchmarkName;
runType: TRunType;
aggregateName: string;
reportLabel: string;
errorOccurred: Boolean;
errorMessage: string;
iterations: TIterationCount;
threads: UInt64;
repetitionIndex: Int64;
repetitions: Int64;
timeUnit: TTimeUnit;
realAccumulatedTime: Double;
cpuAccumulatedTime: Double;
maxHeapBytesUsed: Double;
complexity: TBigO;
complexityLambda: TBigOFunc;
complexityN: UInt64;
statistics: TArray<TStatistics>;
reportBigO: Boolean;
reportRms: Boolean;
counters: TUserCounters;
hasMemoryResult: Boolean;
allocsPerIter: Double;
maxBytesUsed: UInt64;
class function Create: TRun; static;
function GetAdjustedRealTime: Double;
function GetAdjustedCPUTime: Double;
property BenchmarkName: string read GetBenchmarkName;
end;
strict protected
fOutputStream: TStream;
public
function ReportContext(const context: TContext): Boolean; virtual; abstract;
procedure ReportRuns(const reports: TArray<TRun>); virtual; abstract;
procedure PrintBasicContext(var output: System.Text; const context: TContext);
procedure Finalize; virtual;
property OutputStream: TStream write fOutputStream;
end;
TConsoleReporter = class(TBenchmarkReporter)
type
TOutputOption = (
ooColor,
ooTabular
);
TOutputOptions = set of TOutputOption;
const
ooNone = [];
ooColorTabular = [ooColor, ooTabular];
ooDefaults = ooColorTabular;
protected
fOutputOptions: TOutputOptions;
fNameFieldWidth: Integer;
fPrevCounters: TUserCounters;
fPrintedHeader: Boolean;
procedure PrintRunData(const result: TBenchmarkReporter.TRun);
procedure PrintHeader(const run: TBenchmarkReporter.TRun);
public
constructor Create(const opts: TOutputOptions);
function ReportContext(const context: TBenchmarkReporter.TContext): Boolean; override;
procedure ReportRuns(const reports: TArray<TBenchmarkReporter.TRun>); override;
end;
TCSVReporter = class(TBenchmarkReporter)
private
fPrintedHeader: Boolean;
fUserCounterNames: TArray<string>;
procedure PrintRunData(const run: TBenchmarkReporter.TRun);
public
function ReportContext(const context: TBenchmarkReporter.TContext): Boolean; override;
procedure ReportRuns(const reports: TArray<TBenchmarkReporter.TRun>); override;
end;
TJSONReporter = class(TBenchmarkReporter)
private
fFirstReport: Boolean;
procedure PrintRunData(const run: TBenchmarkReporter.TRun);
public
constructor Create;
function ReportContext(const context: TBenchmarkReporter.TContext): Boolean; override;
procedure ReportRuns(const reports: TArray<TBenchmarkReporter.TRun>); override;
procedure Finalize; override;
end;
TBenchmarkRunner = record
type
TRunResults = record
nonAggregates: TArray<TBenchmarkReporter.TRun>;
aggregatesOnly: TArray<TBenchmarkReporter.TRun>;
displayReportAggregatesOnly: Boolean;
fileReportAggregatesOnly: Boolean;
end;
private
runResults: TRunResults;
benchmark: TBenchmarkInstance;
complexityReports: ^TArray<TBenchmarkReporter.TRun>;
minTime: Double;
repeats: Integer;
hasExplicitIterationCount: Boolean;
pool: TArray<TThread>;
iters: TIterationCount;
type TIterationResults = record
results: TThreadManager.TResult;
iters: TIterationCount;
seconds: Double;
end;
function DoNIterations: TIterationResults;
function PredictNumItersNeeded(const i: TIterationResults): TIterationCount;
function ShouldReportIterationResults(const i: TIterationResults): Boolean;
procedure DoOneRepetition(repetitionIndex: Int64);
public
constructor Create(const benchmark: TBenchmarkInstance;
var complexityReports: TArray<TBenchmarkReporter.TRun>);
function GetResults: TRunResults;
end;
const
kRangeMultiplier = 8;
kMaxFamilySize = 100;
kMaxIterations = 1000000000;
{$IFDEF MSWINDOWS}
function QueryProcessCycleTime(ProcessHandle: THandle; var CycleTime: UInt64): BOOL; stdcall;
external kernel32 name 'QueryProcessCycleTime';
function QueryThreadCycleTime(ThreadHandle: THandle; var CycleTime: UInt64): BOOL; stdcall;
external kernel32 name 'QueryThreadCycleTime';