| 1 |
use chrono::naive::NaiveDate; |
| 2 |
use criterion::{black_box, criterion_group, criterion_main, Criterion}; |
| 3 |
|
| 4 |
use chronoutil::delta::{is_leap_year, shift_months}; |
| 5 |
|
| 6 |
fn shift_months_benchmark(c: &mut Criterion) { |
| 7 |
let shifts = black_box(-18..19); |
| 8 |
let base = NaiveDate::from_ymd_opt(2020, 12, 31).unwrap(); |
| 9 |
|
| 10 |
c.bench_function("shift_months", |b| { |
| 11 |
b.iter::<Vec<NaiveDate>, _>(|| shifts.clone().map(|s| shift_months(base, s)).collect()) |
| 12 |
}); |
| 13 |
} |
| 14 |
|
| 15 |
fn in_month(y: i32, m: u32, d: u32) -> bool { |
| 16 |
if m == 4 || m == 6 || m == 9 || m == 11 { |
| 17 |
d <= 30 |
| 18 |
} else if m == 2 { |
| 19 |
d <= 28 || (d == 29 && is_leap_year(y)) |
| 20 |
} else { |
| 21 |
true |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
fn shift_months_many_benchmark(c: &mut Criterion) { |
| 26 |
let shift = black_box(6); |
| 27 |
let mut bases = Vec::new(); |
| 28 |
for y in 0..101 { |
| 29 |
for m in 1..13 { |
| 30 |
for d in 1..31 { |
| 31 |
if in_month(y, m, d) { |
| 32 |
bases.push(NaiveDate::from_ymd_opt(y, m, d).unwrap()); |
| 33 |
} |
| 34 |
} |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
c.bench_function("shift_months_many", |b| { |
| 39 |
b.iter::<Vec<NaiveDate>, _>(|| bases.iter().map(|b| shift_months(*b, shift)).collect()) |
| 40 |
}); |
| 41 |
} |
| 42 |
|
| 43 |
criterion_group!(benches, shift_months_benchmark, shift_months_many_benchmark); |
| 44 |
criterion_main!(benches); |