summaryrefslogtreecommitdiffstats
path: root/third_party/rust/rust_decimal/benches/comparison.rs
blob: d6bf29adba683bf7287815c18ffdf5cba277bbc2 (plain)
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
//! See how `rust-decimal` performs compared to native floating numbers.

use criterion::{
    black_box, criterion_group, criterion_main, measurement::Measurement, BenchmarkGroup, BenchmarkId, Criterion,
};
use rust_decimal::Decimal;

const DECIMAL_2_01: Decimal = Decimal::from_parts(201, 0, 0, false, 2);
const DECIMAL_13_7: Decimal = Decimal::from_parts(137, 0, 0, false, 1);
const F64_2_01: f64 = 2.01;
const F64_13_7: f64 = 13.7;

macro_rules! add_benchmark_group {
    ($criterion:expr, $f:ident, $op:tt) => {
        fn $f<M, const N: usize>(group: &mut BenchmarkGroup<'_, M>)
        where
            M: Measurement,
        {
            group.bench_with_input(BenchmarkId::new("f64 (diff)", N), &N, |ben, _| {
                ben.iter(|| black_box(F64_2_01 $op F64_13_7))
            });

            group.bench_with_input(BenchmarkId::new("f64 (equal)", N), &N, |ben, _| {
                ben.iter(|| black_box(F64_2_01 $op F64_2_01))
            });

            group.bench_with_input(BenchmarkId::new("rust-decimal (diff)", N), &N, |ben, _| {
                ben.iter(|| black_box(DECIMAL_2_01 $op DECIMAL_13_7))
            });

            group.bench_with_input(BenchmarkId::new("rust-decimal (equal)", N), &N, |ben, _| {
                ben.iter(|| black_box(DECIMAL_2_01 $op DECIMAL_2_01))
            });
        }

        let mut group = $criterion.benchmark_group(stringify!($f));
        $f::<_, 100>(&mut group);
        group.finish();
    };
}

fn criterion_benchmark(c: &mut Criterion) {
    add_benchmark_group!(c, addition, +);
    add_benchmark_group!(c, division, /);
    add_benchmark_group!(c, multiplication, *);
    add_benchmark_group!(c, subtraction, -);
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);