-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathluamark.lua
More file actions
1623 lines (1437 loc) · 50.5 KB
/
luamark.lua
File metadata and controls
1623 lines (1437 loc) · 50.5 KB
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
-- luamark - A lightweight, portable micro-benchmarking library.
-- Copyright (c) 2025 Jean-Francois Zinque. MIT License.
---@class luamark
local luamark = {
_VERSION = "1.1.1",
}
local math_ceil = math.ceil
local math_floor = math.floor
local math_max = math.max
local math_min = math.min
local math_random = math.random
local table_sort = table.sort
local jit_flush = jit and jit.flush
local jit_opt_start = jit and jit.opt and jit.opt.start
-- ----------------------------------------------------------------------------
-- Config
-- ----------------------------------------------------------------------------
-- Config defaults balance accuracy vs runtime across function speeds:
-- (config.time=1s, config.rounds=100, MAX_ROUNDS=1000, RESAMPLES=5000)
--
-- | Function | Duration | Rounds | Iterations | Bootstrap | Total |
-- |-------------|----------|--------|------------|-----------|--------|
-- | Very fast | ~1μs | 1,000 | 1,000+ | ~50ms | ~1s |
-- | Fast | ~100μs | 1,000 | 1 | ~50ms | ~150ms |
-- | Medium | ~10ms | 100 | 1 | ~5ms | ~1s |
-- | Slow | ~500ms | 100 | 1 | ~5ms | ~50s |
--
-- MAX_ROUNDS caps total rounds to keep bootstrap CI computation tractable.
-- BOOTSTRAP_RESAMPLES (5k) provides accurate 95% CI for median.
local BOOTSTRAP_RESAMPLES = 5000
local CALIBRATION_PRECISION = 5
local DEFAULT_TERM_WIDTH = 100
local MEMORY_PRECISION = 4
local JIT_MAXTRACE = 20000
local MAX_CALIBRATION_ATTEMPTS = 10
local MAX_ITERATIONS = 1e6
local MAX_ROUNDS = 1000
local config = {
rounds = 100,
time = 1,
}
local TIME = "s"
local MEMORY = "kb"
local COUNT = "count"
---@generic K, V
---@param tbl table<K, V>
---@return K[]
local function sorted_keys(tbl)
local keys = {}
for key in pairs(tbl) do
keys[#keys + 1] = key
end
table_sort(keys)
return keys
end
-- ----------------------------------------------------------------------------
-- Measurement
-- ----------------------------------------------------------------------------
local clock, clock_precision
---@return integer time The minimum measurable time difference based on clock precision
local function get_min_clocktime()
return 10 ^ -clock_precision
end
local CLOCK_PRIORITIES = { "chronos", "posix.time", "socket" }
local NANO_TO_SEC = 1e-9
-- Dispatch loaded module to a function that returns the clock function and clock precision.
local CLOCKS = {
chronos = function(chronos)
return chronos.nanotime, 9
end,
["posix.time"] = function(posix_time)
local posix_clock_gettime = posix_time.clock_gettime
local POSIX_CLOCK_MONOTONIC = posix_time.CLOCK_MONOTONIC
if not posix_clock_gettime then
error("posix.time.clock_gettime is not supported on this OS.")
end
return function()
local ts = posix_clock_gettime(POSIX_CLOCK_MONOTONIC)
return ts.tv_sec + ts.tv_nsec * NANO_TO_SEC
end,
9
end,
socket = function(socket)
return socket.gettime, 4
end,
}
for _, name in ipairs(CLOCK_PRIORITIES) do
local is_installed, module = pcall(require, name)
if is_installed then
local ok, new_clock, new_precision = pcall(CLOCKS[name], module)
if ok and new_clock then
clock, clock_precision = new_clock, new_precision
luamark.clock_name = name
break
end
end
end
if
(not luamark.clock_name or luamark.clock_name == "socket")
and type(love) == "table"
and love.timer
and type(love.timer.getTime) == "function"
then
clock, clock_precision = love.timer.getTime, 6
luamark.clock_name = "love.timer"
end
if not luamark.clock_name then
clock, clock_precision = os.clock, 3
luamark.clock_name = "os.clock"
end
local clock_warning_shown = false
local function warn_low_precision_clock()
if clock_warning_shown or luamark.clock_name ~= "os.clock" then
return
end
clock_warning_shown = true
local msg = "luamark: using os.clock (low precision, CPU time). "
.. "Install chronos, luaposix, or luasocket for better accuracy.\n"
---@diagnostic disable-next-line: deprecated
if warn then
warn(msg) ---@diagnostic disable-line: deprecated
elseif io and io.stderr then
io.stderr:write(msg)
else
print(msg)
end
end
---@alias MeasureOnce fun(fn: function, ctx: any, params: table):number
---@alias Target fun()|{[string]: fun()|luamark.Spec} A function or table of named functions/Specs to benchmark.
---@alias ParamValue string|number|boolean Allowed parameter value types.
-- MeasureOnce functions accept fn, ctx, params to avoid closure overhead.
-- Calling fn(ctx, params) directly eliminates ~64 byte allocation per call.
---@type MeasureOnce
local function measure_time_once(fn, ctx, params)
local start = clock()
fn(ctx, params)
return clock() - start
end
---@type MeasureOnce
local function measure_memory_once(fn, ctx, params)
collectgarbage("collect")
local start = collectgarbage("count")
fn(ctx, params)
return collectgarbage("count") - start
end
-- ----------------------------------------------------------------------------
-- Statistics
-- ----------------------------------------------------------------------------
---@param sorted_samples number[]
---@return number
local function math_median(sorted_samples)
local n = #sorted_samples
local mid = math_floor(n / 2)
if n % 2 == 0 then
return (sorted_samples[mid] + sorted_samples[mid + 1]) / 2
end
return sorted_samples[mid + 1]
end
---@param bootstrap number[]
---@param samples number[]
---@param n integer
---@return number
local function resample_median(bootstrap, samples, n)
for j = 1, n do
bootstrap[j] = samples[math_random(n)]
end
table_sort(bootstrap)
return math_median(bootstrap)
end
--- Calculate 95% CI for median using bootstrap resampling.
---@param samples number[]
---@param n_resamples integer
---@return number lower, number upper
local function bootstrap_ci(samples, n_resamples)
local n = #samples
local bootstrap = {}
local medians = {}
for i = 1, n_resamples do
medians[i] = resample_median(bootstrap, samples, n)
end
table_sort(medians)
-- Clamp indices to valid range for small resample counts
local lower_idx = math_max(1, math_floor(n_resamples * 0.025))
local upper_idx = math_min(n_resamples, math_ceil(n_resamples * 0.975))
return medians[lower_idx], medians[upper_idx]
end
---@param samples number[]
---@return luamark.BaseStats
local function calculate_stats(samples)
local count = #samples
table_sort(samples)
local median = math_median(samples)
local total = 0
for i = 1, count do
total = total + samples[i]
end
local ci_lower, ci_upper, ci_margin
-- Bootstrap CI requires at least 3 samples for meaningful resampling variation
if count >= 3 then
ci_lower, ci_upper = bootstrap_ci(samples, BOOTSTRAP_RESAMPLES)
ci_margin = (ci_upper - ci_lower) / 2
else
ci_lower = median
ci_upper = median
ci_margin = 0
end
return {
median = median,
ci_lower = ci_lower,
ci_upper = ci_upper,
ci_margin = ci_margin,
total = total,
samples = samples,
}
end
-- ----------------------------------------------------------------------------
-- Rendering
-- ----------------------------------------------------------------------------
---@return integer
local get_term_width
do
local ok, system = pcall(require, "system")
if ok and system.termsize then
get_term_width = function()
local rows, cols = system.termsize()
-- termsize returns (nil, error_string) on failure; check rows to detect success
return rows and cols or DEFAULT_TERM_WIDTH
end
else
get_term_width = function()
return DEFAULT_TERM_WIDTH
end
end
end
---@alias default_unit `s` | `kb` | `count`
-- Thresholds relative to input unit (seconds)
local TIME_UNITS = {
{ "m", 60, "%.0f" },
{ "s", 1, "%.0f" },
{ "ms", 1e-3, "%.0f" },
{ "us", 1e-6, "%.0f" },
{ "ns", 1e-9, "%.0f" },
}
-- Thresholds relative to input unit (kilobytes)
local MEMORY_UNITS = {
{ "TB", 1024 ^ 3, "%.0f" },
{ "GB", 1024 ^ 2, "%.0f" },
{ "MB", 1024, "%.0f" },
{ "kB", 1, "%.0f" },
{ "B", 1 / 1024, "%.0f" },
}
local COUNT_UNITS = {
{ "M", 1e6, "%.1f" },
{ "k", 1e3, "%.1f" },
{ "", 1, "%.1f" },
}
local UNITS = {
[TIME] = { label = "Time", scales = TIME_UNITS },
[MEMORY] = { label = "Memory", scales = MEMORY_UNITS },
[COUNT] = { scales = COUNT_UNITS },
}
local RENDER_UNITS = { TIME, MEMORY }
local BAR_CHAR = "█"
local BAR_MAX_WIDTH = 20
local BAR_MIN_WIDTH = 10
local NAME_MIN_WIDTH = 4
local ELLIPSIS = "..."
local EMBEDDED_BAR_WIDTH = 8
local SUMMARIZE_HEADERS = {
"name",
"rank",
"relative",
"median",
"ops",
}
local HEADER_LABELS = {
name = "Name",
rank = "Rank",
relative = "Relative",
median = "Median",
ops = "Ops",
}
---@param str string
---@return string
local function trim_zeroes(str)
if not str:find("%.") then
return str
end
return (str:gsub("%.?0+$", ""))
end
---@param str string
---@return integer
local function utf8_width(str)
local width = 0
for i = 1, #str do
local byte = string.byte(str, i)
-- Skip UTF-8 continuation bytes (0x80-0xBF)
if byte < 0x80 or byte >= 0xC0 then
width = width + 1
end
end
return width
end
---@param str string
---@param width integer
---@return string
local function align_left(str, width)
return str .. string.rep(" ", width - utf8_width(str))
end
---@param str string
---@param width integer
---@return string
local function align_right(str, width)
return string.rep(" ", width - utf8_width(str)) .. str
end
---@param str string
---@param width integer
---@return string
local function center(str, width)
local total_padding = math_max(0, width - utf8_width(str))
local left_padding = math_floor(total_padding / 2)
local right_padding = total_padding - left_padding
return string.rep(" ", left_padding) .. str .. string.rep(" ", right_padding)
end
---@param t string[]
---@return string
local function concat_line(t)
return table.concat(t, " ")
end
---@param name string
---@param max_len integer
---@return string
local function truncate_name(name, max_len)
if #name <= max_len then
return name
end
if max_len <= #ELLIPSIS then
return name:sub(1, max_len)
end
return name:sub(1, max_len - #ELLIPSIS) .. ELLIPSIS
end
---@param value number Value to format.
---@param unit_type default_unit Unit type: "s" (time), "kb" (memory), or "count".
---@return string
local function humanize(value, unit_type)
local units = UNITS[unit_type].scales
for i = 1, #units do
local symbol, threshold, fmt = units[i][1], units[i][2], units[i][3]
if value >= threshold then
return trim_zeroes(string.format(fmt, value / threshold)) .. symbol
end
end
return "0" .. units[#units][1]
end
---@param median number
---@param margin number
---@param unit default_unit
---@return string
local function format_median(median, margin, unit)
local margin_str = humanize(margin, unit)
if margin_str:match("^0") then
return humanize(median, unit)
end
return humanize(median, unit) .. " ± " .. margin_str
end
---@param stats luamark.Stats
---@return string
local function render_stats(stats)
local unit = stats.unit
local lines = {
"Median: " .. humanize(stats.median, unit),
string.format(
"CI: %s - %s (± %s)",
humanize(stats.ci_lower, unit),
humanize(stats.ci_upper, unit),
humanize(stats.ci_margin, unit)
),
}
if stats.ops then
lines[#lines + 1] = "Ops: " .. humanize(stats.ops, COUNT) .. "/s"
end
lines[#lines + 1] = "Rounds: " .. stats.rounds
lines[#lines + 1] = "Total: " .. humanize(stats.total, unit)
return table.concat(lines, "\n")
end
--- Format relative with arrow: 1x (baseline), ↑Nx (faster), ↓Nx (slower).
---@param relative number|nil
---@return string
local function format_relative(relative)
if not relative then
return ""
end
if relative == 1 then
return "1x"
elseif relative < 1 then
return "↑" .. trim_zeroes(string.format("%.2f", 1 / relative)) .. "x"
else
return "↓" .. trim_zeroes(string.format("%.2f", relative)) .. "x"
end
end
---@param stats luamark.Stats|luamark.Result
---@return table<string, string>
local function format_row(stats)
local unit = stats.unit
-- Format rank with approximate marker if CIs overlap
local rank_str = ""
if stats.rank then
local prefix = stats.is_approximate and "≈" or ""
rank_str = prefix .. stats.rank
end
return {
rank = rank_str,
relative = format_relative(stats.relative),
median = format_median(stats.median, stats.ci_margin, unit),
ops = stats.ops and (humanize(stats.ops, COUNT) .. "/s") or "",
}
end
---@param rows table[]
---@return integer[]
local function calculate_column_widths(rows)
local widths = {}
for col, header in ipairs(SUMMARIZE_HEADERS) do
local max_width = utf8_width(HEADER_LABELS[header])
for row = 1, #rows do
max_width = math_max(max_width, utf8_width(rows[row][header] or ""))
end
widths[col] = max_width
end
return widths
end
--- Mutates rows and widths in place.
---@param rows table[]
---@param widths integer[]
---@param max_width integer
local function fit_names_inplace(rows, widths, max_width)
local other_width = 0
for i = 2, #SUMMARIZE_HEADERS do
other_width = other_width + widths[i]
end
local bar_col_width = EMBEDDED_BAR_WIDTH + 2
local max_name = math_max(
NAME_MIN_WIDTH,
max_width - other_width - (#SUMMARIZE_HEADERS - 1) * 2 - bar_col_width
)
if widths[1] > max_name then
widths[1] = max_name
for i = 1, #rows do
rows[i].name = truncate_name(rows[i].name, max_name)
end
end
end
---@param relative_str string
---@param bar_width integer
---@param max_relative_width integer
---@return string
local function build_relative_bar(relative_str, bar_width, max_relative_width)
local bar = string.rep(BAR_CHAR, bar_width)
local padded_bar = bar .. string.rep(" ", EMBEDDED_BAR_WIDTH - bar_width)
-- Use utf8_width for UTF-8 aware padding (arrows are multi-byte)
local padded_relative = string.rep(" ", max_relative_width - utf8_width(relative_str))
.. relative_str
return padded_bar .. " " .. padded_relative
end
---@param rows {name: string, relative: string, median: string, median_value: number}[]
---@param max_width? integer
---@return string[]
local function render_bar_chart(rows, max_width)
max_width = max_width or get_term_width()
local max_median = 0
local max_suffix_len = 0
local max_name_len = NAME_MIN_WIDTH
for i = 1, #rows do
local row = rows[i]
max_median = math_max(max_median, row.median_value)
-- Suffix format: " relative (median)" -> " " + " (" + ")" = 3 fixed chars
max_suffix_len = math_max(max_suffix_len, 3 + utf8_width(row.relative) + #row.median)
max_name_len = math_max(max_name_len, utf8_width(row.name))
end
-- Calculate column widths
local available = max_width - 3 - max_suffix_len
local bar_max = math_max(BAR_MIN_WIDTH, math_min(BAR_MAX_WIDTH, available - NAME_MIN_WIDTH))
local name_max = math_max(NAME_MIN_WIDTH, math_min(max_name_len, available - bar_max))
local lines = {}
for i = 1, #rows do
local row = rows[i]
-- Scale bar by median (smaller bar = less time = faster)
local bar_width = math_max(1, math_floor((row.median_value / max_median) * bar_max))
local name = align_left(truncate_name(row.name, name_max), name_max)
local bar = string.rep(BAR_CHAR, bar_width)
lines[i] = string.format("%s |%s %s (%s)", name, bar, row.relative, row.median)
end
return lines
end
-- Columns that should be right-aligned
local RIGHT_ALIGN_COLS = { rank = true, median = true, ops = true }
---@param rows table[]
---@param widths integer[]
---@param show_ops boolean
---@return string
local function render_plain_table(rows, widths, show_ops)
local max_median = 0
local max_relative_width = 0
for i = 1, #rows do
max_median = math_max(max_median, rows[i].median_value)
max_relative_width = math_max(max_relative_width, utf8_width(rows[i].relative))
end
local relative_bar_width = EMBEDDED_BAR_WIDTH + max_relative_width + 1
local visible_headers = {}
for i, header in ipairs(SUMMARIZE_HEADERS) do
if header ~= "ops" or show_ops then
visible_headers[#visible_headers + 1] = { idx = i, name = header }
end
end
local header_cells, underline_cells = {}, {}
for _, col in ipairs(visible_headers) do
local width = (col.name == "relative") and relative_bar_width or widths[col.idx]
header_cells[#header_cells + 1] = center(HEADER_LABELS[col.name], width)
underline_cells[#underline_cells + 1] = string.rep("-", width)
end
local lines = { concat_line(header_cells), concat_line(underline_cells) }
for r = 1, #rows do
local row = rows[r]
local cells = {}
for _, col in ipairs(visible_headers) do
if col.name == "relative" then
-- Scale bar by median (smaller bar = less time = faster)
local bar_width =
math_max(1, math_floor((row.median_value / max_median) * EMBEDDED_BAR_WIDTH))
cells[#cells + 1] = align_left(
build_relative_bar(row.relative, bar_width, max_relative_width),
relative_bar_width
)
elseif RIGHT_ALIGN_COLS[col.name] then
cells[#cells + 1] = align_right(row[col.name], widths[col.idx])
else
cells[#cells + 1] = align_left(row[col.name], widths[col.idx])
end
end
lines[#lines + 1] = concat_line(cells)
end
return table.concat(lines, "\n")
end
---@param results luamark.Result[]
---@param format "plain"|"compact"
---@param max_width? integer
---@return string
local function render_summary(results, format, max_width)
local rows = {}
for i = 1, #results do
local row = format_row(results[i])
row.name = results[i].name
---@diagnostic disable-next-line: assign-type-mismatch
row.median_value = results[i].median
rows[i] = row
end
max_width = max_width or get_term_width()
if format == "compact" then
return table.concat(render_bar_chart(rows, max_width), "\n")
end
local show_ops = results[1] and results[1].unit == TIME
local widths = calculate_column_widths(rows)
fit_names_inplace(rows, widths, max_width)
return render_plain_table(rows, widths, show_ops)
end
-- ----------------------------------------------------------------------------
-- Benchmark
-- ----------------------------------------------------------------------------
---@generic K, V
---@param tbl table<K, V>
---@return table<K, V>
local function shallow_copy(tbl)
local copy = {}
for key, value in pairs(tbl) do
copy[key] = value
end
return copy
end
local MAX_PARAM_COMBINATIONS = 10000
---@param params table<string, any[]>?
---@return table[]
local function expand_params(params)
if not params or not next(params) then
return { {} }
end
-- Check for combinatorial explosion before allocating
local total_combinations = 1
for _, values in pairs(params) do
total_combinations = total_combinations * #values
if total_combinations > MAX_PARAM_COMBINATIONS then
error(
string.format(
"Too many parameter combinations (exceeds %d). Reduce the number of parameter values.",
MAX_PARAM_COMBINATIONS
)
)
end
end
-- Build combinations iteratively: for each parameter, expand existing combinations
local combos = { {} }
local keys = sorted_keys(params)
for i = 1, #keys do
local name = keys[i]
local values = params[name]
local new_combos = {}
for j = 1, #combos do
local combo = combos[j]
for k = 1, #values do
local new_combo = shallow_copy(combo)
new_combo[name] = values[k]
new_combos[#new_combos + 1] = new_combo
end
end
combos = new_combos
end
return combos
end
-- Offset above 0.5 to handle floating-point edge cases in rounding
local ROUNDING_EPSILON = 0.50000000000008
---@param num number
---@param precision integer
---@return number
local function math_round(num, precision)
local mul = 10 ^ precision
local rounded
if num > 0 then
rounded = math_floor(num * mul + ROUNDING_EPSILON) / mul
else
rounded = math_ceil(num * mul - ROUNDING_EPSILON) / mul
end
return math_max(rounded, 10 ^ -precision)
end
---@alias Measure fun(fn: function, iterations: integer, setup?: function, teardown?: function, get_ctx?: function, params?: table): number, number
---@param measure_once MeasureOnce
---@param precision integer
---@return Measure
local function build_measure(measure_once, precision)
return function(fn, iterations, setup, teardown, get_ctx, params)
local total = 0
local ctx = get_ctx and get_ctx() or nil
for _ = 1, iterations do
if setup then
setup()
end
if get_ctx then
ctx = get_ctx()
end
total = total + measure_once(fn, ctx, params)
if teardown then
teardown()
end
end
return total, math_round(total / iterations, precision)
end
end
---@param precision integer
---@return Measure
local function build_measure_time(precision)
local slow_path = build_measure(measure_time_once, precision)
return function(fn, iterations, setup, teardown, get_ctx, params)
-- Fast path: 2 clock() calls total instead of 2N when no hooks need to run
-- between iterations. Reduces timing overhead for fast functions.
if not setup and not teardown then
local ctx = get_ctx and get_ctx() or nil
local t1 = clock()
for _ = 1, iterations do
fn(ctx, params)
end
local total = clock() - t1
return total, math_round(total / iterations, precision)
end
return slow_path(fn, iterations, setup, teardown, get_ctx, params)
end
end
local measure_time = build_measure_time(clock_precision)
local measure_memory = build_measure(measure_memory_once, MEMORY_PRECISION)
local ZERO_TIME_SCALE = 100
---@param fn function The function to benchmark.
---@param setup? function Function executed before each iteration.
---@param teardown? function Function executed after each iteration.
---@param get_ctx function Function that returns current iteration context.
---@param params table Parameter table to pass to fn.
---@return integer # Number of iterations per round.
local function calibrate_iterations(fn, setup, teardown, get_ctx, params)
local min_time = get_min_clocktime() * CALIBRATION_PRECISION
local iterations = 1
for _ = 1, MAX_CALIBRATION_ATTEMPTS do
local total_time = measure_time(fn, iterations, setup, teardown, get_ctx, params)
if total_time >= min_time then
break
end
local scale
if total_time > 0 then
scale = min_time / total_time
else
scale = ZERO_TIME_SCALE
end
iterations = math_ceil(iterations * scale)
if iterations >= MAX_ITERATIONS then
return MAX_ITERATIONS
end
end
return iterations
end
---@param round_duration number
---@return integer rounds
---@return number time
local function calibrate_stop(round_duration)
-- Guard against division by zero for extremely fast functions on low-precision clocks.
local safe_duration = round_duration
if round_duration <= 0 then
safe_duration = get_min_clocktime()
end
local time = math_max(config.rounds * safe_duration, config.time)
local rounds = math_min(MAX_ROUNDS, math_ceil(time / safe_duration))
return rounds, time
end
---@param fn any
---@param rounds? number
---@param time? number
---@param setup? function
---@param teardown? function
local function validate_benchmark_args(fn, rounds, time, setup, teardown)
assert(type(fn) == "function", "'fn' must be a function, got " .. type(fn))
assert(rounds == nil or rounds > 0, "'rounds' must be > 0.")
assert(not time or time > 0, "'time' must be > 0.")
assert(setup == nil or type(setup) == "function", "'setup' must be a function")
assert(teardown == nil or type(teardown) == "function", "'teardown' must be a function")
end
local COMMON_OPTS = {
rounds = "number",
time = "number",
setup = "function",
teardown = "function",
}
local SUITE_ONLY_OPTS = {
params = "table",
}
--- Validate options against allowed types.
---@param opts table Options to validate.
---@param extra_opts? table<string, string> Additional valid options beyond COMMON_OPTS.
local function validate_options(opts, extra_opts)
for key, value in pairs(opts) do
local expected_type = COMMON_OPTS[key] or (extra_opts and extra_opts[key])
if not expected_type then
error("Unknown option: " .. key)
end
if type(value) ~= expected_type then
error(string.format("Option '%s' should be %s", key, expected_type))
end
end
if opts.rounds and opts.rounds ~= math_floor(opts.rounds) then
error("Option 'rounds' must be an integer")
end
end
--- Validate params table structure.
---@param params table<string, ParamValue[]> Parameter combinations.
local function validate_params(params)
for name, values in pairs(params) do
if type(name) ~= "string" then
error(string.format("params key must be a string, got %s", type(name)))
end
if type(values) ~= "table" then
error(string.format("params['%s'] must be an array, got %s", name, type(values)))
end
if #values == 0 then
error(string.format("params['%s'] must not be empty", name))
end
for i, v in ipairs(values) do
local vtype = type(v)
if vtype ~= "string" and vtype ~= "number" and vtype ~= "boolean" then
error(
string.format(
"params['%s'][%d] must be string, number, or boolean, got %s",
name,
i,
vtype
)
)
end
end
end
end
--- Validate options for single API (timeit/memit).
--- Reject params option with helpful error message.
---@param opts luamark.Options Options to validate.
local function validate_single_options(opts)
---@diagnostic disable-next-line: undefined-field
if opts.params then
error("'params' is not supported in timeit/memit. Use compare_time/compare_memory instead.")
end
validate_options(opts)
end
--- Validate options for suite API (compare_time/compare_memory).
---@param opts luamark.SuiteOptions Options to validate.
local function validate_suite_options(opts)
validate_options(opts, SUITE_ONLY_OPTS)
if opts.params then
validate_params(opts.params)
end
end
--- Validate funcs table for suite API (compare_time/compare_memory).
--- Reject numeric keys (arrays) since function names must be strings.
---@param funcs table Table of functions to validate.
local function validate_funcs(funcs)
for key in pairs(funcs) do
if type(key) ~= "string" then
error(
"'funcs' keys must be strings, got " .. type(key) .. ". Use named keys: { name = fn }"
)
end
end
end
---@param samples number[] Raw measurement samples.
---@param rounds integer Number of benchmark rounds executed.
---@param iterations integer Number of iterations per round.
---@param timestamp string ISO 8601 UTC timestamp.
---@param unit default_unit Measurement unit.
---@return luamark.Stats
local function build_stats_result(samples, rounds, iterations, timestamp, unit)
local stats = calculate_stats(samples) ---@cast stats luamark.Stats
stats.rounds = rounds
stats.iterations = iterations
stats.timestamp = timestamp
stats.unit = unit
if unit == TIME and stats.median > 0 then
stats.ops = 1 / stats.median
end
setmetatable(stats, {
__tostring = function(self)
return format_median(self.median, self.ci_margin, unit)
end,
})
return stats
end
-- Sentinel to avoid creating new tables for single mode (timeit/memit).
local EMPTY_PARAMS = {}
--- Run a benchmark on a function using a specified measurement method.
---@param fn luamark.Fun Function to benchmark.
---@param measure Measure Measurement function (e.g., measure_time or measure_memory).
---@param suspend_gc boolean Controls garbage collection during benchmark.
---@param unit default_unit Measurement unit.
---@param rounds? number Number of rounds.
---@param time? number Target duration in seconds.
---@param setup? function Runs once before benchmark, returns context.
---@param teardown? function Runs once after benchmark.
---@param params? table Parameter values for this run.
---@param before? function Per-iteration setup (from Spec), returns iteration context.
---@param after? function Per-iteration teardown (from Spec).
---@return luamark.Stats
local function single_benchmark(
fn,
measure,
suspend_gc,
unit,
rounds,
time,
setup,
teardown,
params,
before,
after
)
validate_benchmark_args(fn, rounds, time, setup, teardown)
warn_low_precision_clock()
params = params or EMPTY_PARAMS
local ctx
if setup then
ctx = setup(params)
end
-- Using a closure avoids creating a new function per iteration.
local iteration_ctx = ctx
local function get_ctx()
return iteration_ctx
end
-- Per-iteration setup from Spec.before.
-- The hook can return a new context; otherwise the previous context is preserved.
local iteration_setup
if before then