[go: up one dir, main page]

divan 0.1.11

Statistically-comfy benchmarking library.
Documentation
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
//! Tests every benchmarking loop combination in `Bencher`. When run under Miri,
//! this catches memory leaks and UB in `unsafe` code.

use std::{
    collections::HashSet,
    sync::atomic::{AtomicUsize, Ordering::SeqCst},
};

use super::*;
use crate::{
    config::Action,
    time::{Timer, TimerKind},
};

// We use a small number of runs because Miri is very slow.
const SAMPLE_COUNT: u32 = 3;

const SAMPLE_SIZE: u32 = 2;

// Tests `SAMPLE_COUNT` by including it in the middle and having higher numbers
// where `SAMPLE_COUNT % n != 0`.
const THREAD_COUNTS: &[usize] = if cfg!(miri) {
    // Speed up Miri tests while still catching UB/memory issues.
    &[1, 2]
} else {
    // Exhaustively test expectations.
    //
    // Tests `SAMPLE_COUNT` by:
    // - Including it in the middle
    // - Having numbers where `SAMPLE_COUNT % n` varies
    &[1, 2, 3, 4, 5, 6, 9]
};

#[track_caller]
fn test_bencher(test: &mut dyn FnMut(Bencher)) {
    let bench_options = BenchOptions {
        sample_count: Some(SAMPLE_COUNT),
        sample_size: Some(SAMPLE_SIZE),
        ..BenchOptions::default()
    };

    for timer in Timer::available() {
        for action in [Action::Bench, Action::Test] {
            let shared_context =
                SharedContext { action, timer, bench_overhead: FineDuration::default() };

            for &thread_count in THREAD_COUNTS {
                let mut bench_context = BenchContext::new(
                    &shared_context,
                    &bench_options,
                    NonZeroUsize::new(thread_count).unwrap(),
                );

                test(Bencher::new(&mut bench_context));

                assert!(bench_context.did_run);

                let samples = &bench_context.samples;

                // '--test' should run the expected number of times but not
                // allocate any samples.
                if action.is_test() {
                    assert_eq!(samples.time_samples.capacity(), 0);
                }

                if action.is_test() || thread_count == 1 {
                    assert_eq!(samples.threads.capacity(), 0);
                }

                if thread_count > 1 {
                    assert_eq!(
                        samples.threads.len() * thread_count,
                        samples.time_samples.len(),
                        "Thread sample count must be a multiple of total sample count"
                    );
                }
            }
        }
    }
}

fn make_string() -> String {
    ('a'..='z').collect()
}

/// Tests that the benchmarked function runs the expected number of times when
/// running either in benchmark or test mode.
///
/// Tests operate over all input/output combinations of:
/// - `()`
/// - `i32`
/// - `String`
/// - Zero sized type (ZST) that implements `Drop`
///
/// This ensures that any special handling of `size_of` or `needs_drop` does not
/// affect the number of runs.
#[allow(clippy::unused_unit)]
mod run_count {
    use super::*;

    fn test(run_bench: fn(Bencher, &(dyn Fn() + Sync))) {
        test_with_drop_counter(&AtomicUsize::new(usize::MAX), run_bench);
    }

    fn test_with_drop_counter(
        drop_count: &AtomicUsize,
        run_bench: fn(Bencher, &(dyn Fn() + Sync)),
    ) {
        let test_drop_count = drop_count.load(SeqCst) != usize::MAX;

        let bench_count = AtomicUsize::new(0);
        let test_count = AtomicUsize::new(0);

        let mut thread_counts = HashSet::<u32>::new();
        let mut timer_os = false;
        let mut timer_tsc = false;

        test_bencher(&mut |bencher| {
            let context = &bencher.context;

            let thread_count = context.thread_count.get();
            thread_counts.insert(thread_count as u32);

            match context.shared_context.timer.kind() {
                TimerKind::Os => timer_os = true,
                TimerKind::Tsc => timer_tsc = true,
            }

            let is_test = context.shared_context.action.is_test();

            let shared_run_count = if is_test { &test_count } else { &bench_count };
            let start_run_count = shared_run_count.load(SeqCst);

            run_bench(bencher, &|| {
                shared_run_count.fetch_add(1, SeqCst);
            });

            let end_run_count = shared_run_count.load(SeqCst);
            let run_count = end_run_count - start_run_count;

            if is_test {
                assert_eq!(run_count, thread_count);
            } else {
                let expected_samples = match SAMPLE_COUNT as usize % thread_count {
                    0 => SAMPLE_COUNT,
                    rem => SAMPLE_COUNT + (thread_count - rem) as u32,
                };

                let expected_iters = (expected_samples * SAMPLE_SIZE) as usize;
                assert_eq!(run_count, expected_iters);
            }
        });

        let thread_count = thread_counts.into_iter().sum::<u32>();

        let timer_count = timer_os as u32 + timer_tsc as u32;
        let bench_count = bench_count.into_inner() as u32;
        let test_count = test_count.into_inner() as u32;

        let total_count = bench_count + test_count;
        assert_ne!(total_count, 0);

        // The drop count should equal the total run count.
        if test_drop_count {
            assert_eq!(drop_count.load(SeqCst), total_count as usize);
        }

        assert_eq!(test_count, timer_count * thread_count);
    }

    #[test]
    fn bench() {
        struct DroppedZst;

        static ZST_DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

        impl Drop for DroppedZst {
            fn drop(&mut self) {
                ZST_DROP_COUNT.fetch_add(1, SeqCst);
            }
        }

        // `()` out.
        test(|b, f| b.bench(f));

        // `i32` out.
        test(|b, f| {
            b.bench(|| -> i32 {
                f();
                100i32
            })
        });

        // `String` out.
        test(|b, f| {
            b.bench(|| -> String {
                f();
                make_string()
            })
        });

        // `DroppedZst` out.
        test_with_drop_counter(&ZST_DROP_COUNT, |b, f| {
            b.bench(|| -> DroppedZst {
                f();
                DroppedZst
            })
        });
    }

    #[test]
    fn bench_values() {
        struct DroppedZst;

        static ZST_DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

        impl Drop for DroppedZst {
            fn drop(&mut self) {
                ZST_DROP_COUNT.fetch_add(1, SeqCst);
            }
        }

        let test_zst_drop = |run_bench| {
            ZST_DROP_COUNT.store(0, SeqCst);
            test_with_drop_counter(&ZST_DROP_COUNT, run_bench);
        };

        // `()` in, `()` out.
        test(|b, f| b.with_inputs(|| ()).bench_values(|_: ()| -> () { f() }));

        // `()` in, `i32` out.
        test(|b, f| {
            b.with_inputs(|| ()).bench_values(|_: ()| -> i32 {
                f();
                100i32
            })
        });

        // `()` in, `String` out.
        test(|b, f| {
            b.with_inputs(|| ()).bench_values(|_: ()| -> String {
                f();
                make_string()
            })
        });

        // `()` in, `DroppedZst` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| ()).bench_values(|_: ()| -> DroppedZst {
                f();
                DroppedZst
            })
        });

        // `i32` in, `()` out.
        test(|b, f| b.with_inputs(|| 100i32).bench_values(|_: i32| -> () { f() }));

        // `i32` in, `i32` out.
        test(|b, f| {
            b.with_inputs(|| 100i32).bench_values(|value: i32| -> i32 {
                f();
                value
            })
        });

        // `i32` in, `String` out.
        test(|b, f| {
            b.with_inputs(|| 100i32).bench_values(|_: i32| -> String {
                f();
                make_string()
            })
        });

        // `i32` in, `DroppedZst` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| 100i32).bench_values(|_: i32| -> DroppedZst {
                f();
                DroppedZst
            })
        });

        // `String` in, `()` out.
        test(|b, f| b.with_inputs(make_string).bench_values(|_: String| -> () { f() }));

        // `String` in, `i32` out.
        test(|b, f| {
            b.with_inputs(make_string).bench_values(|_: String| -> i32 {
                f();
                100i32
            })
        });

        // `String` in, `String` out.
        test(|b, f| {
            b.with_inputs(make_string).bench_values(|value: String| -> String {
                f();
                value
            })
        });

        // `String` in, `DroppedZst` out.
        test_zst_drop(|b, f| {
            b.with_inputs(make_string).bench_values(|_: String| -> DroppedZst {
                f();
                DroppedZst
            })
        });

        // `DroppedZst` in, `()` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| DroppedZst).bench_values(|_: DroppedZst| -> () { f() })
        });

        // `DroppedZst` in, `i32` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| DroppedZst).bench_values(|_: DroppedZst| -> i32 {
                f();
                100i32
            })
        });

        // `DroppedZst` in, `String` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| DroppedZst).bench_values(|_: DroppedZst| -> String {
                f();
                make_string()
            })
        });

        // `DroppedZst` in, `DroppedZst` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| DroppedZst).bench_values(|value: DroppedZst| -> DroppedZst {
                f();
                value
            })
        });
    }

    #[test]
    fn bench_refs() {
        struct DroppedZst;

        static ZST_DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

        impl Drop for DroppedZst {
            fn drop(&mut self) {
                ZST_DROP_COUNT.fetch_add(1, SeqCst);
            }
        }

        let test_zst_drop = |run_bench| {
            ZST_DROP_COUNT.store(0, SeqCst);
            test_with_drop_counter(&ZST_DROP_COUNT, run_bench);
        };

        // `&mut ()` in, `()` out.
        test(|b, f| b.with_inputs(|| ()).bench_refs(|_: &mut ()| -> () { f() }));

        // `&mut ()` in, `i32` out.
        test(|b, f| {
            b.with_inputs(|| ()).bench_refs(|_: &mut ()| -> i32 {
                f();
                100i32
            })
        });

        // `&mut ()` in, `String` out.
        test(|b, f| {
            b.with_inputs(|| ()).bench_refs(|_: &mut ()| -> String {
                f();
                make_string()
            })
        });

        // `&mut ()` in, `DroppedZst` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| ()).bench_refs(|_: &mut ()| -> DroppedZst {
                f();
                DroppedZst
            })
        });

        // `&mut i32` in, `()` out.
        test(|b, f| b.with_inputs(|| 100i32).bench_refs(|_: &mut i32| -> () { f() }));

        // `&mut i32` in, `i32` out.
        test(|b, f| {
            b.with_inputs(|| 100i32).bench_refs(|value: &mut i32| -> i32 {
                f();
                *value
            })
        });

        // `&mut i32` in, `String` out.
        test(|b, f| {
            b.with_inputs(|| 100i32).bench_refs(|_: &mut i32| -> String {
                f();
                make_string()
            })
        });

        // `&mut i32` in, `DroppedZst` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| 100i32).bench_refs(|_: &mut i32| -> DroppedZst {
                f();
                DroppedZst
            })
        });

        // `&mut String` in, `()` out.
        test(|b, f| b.with_inputs(make_string).bench_refs(|_: &mut String| -> () { f() }));

        // `&mut String` in, `i32` out.
        test(|b, f| {
            b.with_inputs(make_string).bench_refs(|_: &mut String| -> i32 {
                f();
                100i32
            })
        });

        // `&mut String` in, `String` out.
        test(|b, f| {
            b.with_inputs(make_string).bench_refs(|value: &mut String| -> String {
                f();
                value.clone()
            })
        });

        // `&mut String` in, `DroppedZst` out.
        test_zst_drop(|b, f| {
            b.with_inputs(make_string).bench_refs(|_: &mut String| -> DroppedZst {
                f();
                DroppedZst
            })
        });

        // `&mut DroppedZst` in, `()` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| DroppedZst).bench_refs(|_: &mut DroppedZst| -> () { f() })
        });

        // `&mut DroppedZst` in, `i32` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| DroppedZst).bench_refs(|_: &mut DroppedZst| -> i32 {
                f();
                100i32
            })
        });

        // `&mut DroppedZst` in, `String` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| DroppedZst).bench_refs(|_: &mut DroppedZst| -> String {
                f();
                make_string()
            })
        });

        // `&mut DroppedZst` in, `DroppedZst` out.
        test_zst_drop(|b, f| {
            b.with_inputs(|| {
                // Adjust counter for input ZST.
                ZST_DROP_COUNT.fetch_sub(1, SeqCst);

                DroppedZst
            })
            .bench_refs(|_: &mut DroppedZst| -> DroppedZst {
                f();
                DroppedZst
            })
        });
    }
}

mod no_input {
    use super::*;

    #[test]
    fn string_output() {
        test_bencher(&mut |b| b.bench(make_string));
    }

    #[test]
    fn no_output() {
        test_bencher(&mut |b| b.bench(|| black_box_drop(make_string())));
    }
}

mod string_input {
    use super::*;

    #[test]
    fn string_output() {
        test_bencher(&mut |b| b.with_inputs(make_string).bench_values(|s| s.to_ascii_uppercase()));
    }

    #[test]
    fn no_output() {
        test_bencher(&mut |b| b.with_inputs(make_string).bench_refs(|s| s.make_ascii_uppercase()));
    }
}

mod zst_input {
    use super::*;

    #[test]
    fn zst_output() {
        struct DroppedZst;

        // Each test has its own `ZST_COUNT` global because tests are run
        // independently in parallel.
        static ZST_COUNT: AtomicUsize = AtomicUsize::new(0);

        impl Drop for DroppedZst {
            fn drop(&mut self) {
                ZST_COUNT.fetch_sub(1, SeqCst);
            }
        }

        test_bencher(&mut |b| {
            b.with_inputs(|| {
                ZST_COUNT.fetch_add(1, SeqCst);
                DroppedZst
            })
            .bench_values(black_box);
        });

        assert_eq!(ZST_COUNT.load(SeqCst), 0);
    }

    #[test]
    fn no_output() {
        struct DroppedZst;

        static ZST_COUNT: AtomicUsize = AtomicUsize::new(0);

        impl Drop for DroppedZst {
            fn drop(&mut self) {
                ZST_COUNT.fetch_sub(1, SeqCst);
            }
        }

        test_bencher(&mut |b| {
            b.with_inputs(|| {
                ZST_COUNT.fetch_add(1, SeqCst);
                DroppedZst
            })
            .bench_values(drop);
        });

        assert_eq!(ZST_COUNT.load(SeqCst), 0);
    }
}