Skip to content

Commit 8afadfc

Browse files
authored
bechmark: add min, max & avg to recorded measurements (#22078)
1 parent e7c2295 commit 8afadfc

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

vlib/benchmark/benchmark.v

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ module benchmark
22

33
import time
44
import term
5+
import arrays
56

67
pub const b_ok = term.ok_message('OK ')
78
pub const b_fail = term.fail_message('FAIL')
@@ -24,6 +25,7 @@ pub mut:
2425
bok string
2526
bfail string
2627
measured_steps []string
28+
step_data map[string][]f64
2729
}
2830

2931
// new_benchmark returns a `Benchmark` instance on the stack.
@@ -145,6 +147,7 @@ pub fn (mut b Benchmark) record_measure(label string) i64 {
145147
b.ok()
146148
res := b.step_timer.elapsed().microseconds()
147149
b.measured_steps << b.step_message_with_label(benchmark.b_spent, 'in ${label}')
150+
b.step_data[label] << res
148151
b.step()
149152
return res
150153
}
@@ -244,6 +247,12 @@ pub fn (b &Benchmark) total_message(msg string) string {
244247
}
245248
}
246249
tmsg += '${b.ntotal} total. ${term.colorize(term.bold, 'Elapsed time:')} ${b.bench_timer.elapsed().microseconds() / 1000} ms${njobs_label}.'
250+
if msg in b.step_data && b.step_data[msg].len > 1 {
251+
min := arrays.min(b.step_data[msg]) or { 0 } / 1000.0
252+
max := arrays.max(b.step_data[msg]) or { 0 } / 1000.0
253+
avg := (arrays.sum(b.step_data[msg]) or { 0 } / b.step_data[msg].len) / 1000.0
254+
tmsg += ' Min: ${min:.3f} ms. Max: ${max:.3f} ms. Avg: ${avg:.3f} ms'
255+
}
247256
return tmsg
248257
}
249258

vlib/benchmark/benchmark_test.v

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,29 @@ fn test_record_measure() {
3636
assert res.contains('ms in sleeping 1')
3737
assert res.contains('SPENT')
3838
}
39+
40+
fn test_total_message() {
41+
mut b := benchmark.start()
42+
for _ in 0 .. 100 {
43+
time.sleep(time.millisecond)
44+
x := b.record_measure('sleeping 1')
45+
assert x > 1_000
46+
}
47+
48+
res := b.total_message('sleeping 1')
49+
println(res)
50+
51+
assert res.contains(' Min: ')
52+
assert res.contains(' Max: ')
53+
assert res.contains(' Avg: ')
54+
55+
time.sleep(time.millisecond)
56+
y := b.record_measure('sleeping 2')
57+
assert y > 1_000
58+
// Should not contain min max avg, insufficient information
59+
res2 := b.total_message('sleeping 2')
60+
61+
assert !res2.contains(' Min: ')
62+
assert !res2.contains(' Max: ')
63+
assert !res2.contains(' Avg: ')
64+
}

0 commit comments

Comments
 (0)