use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; use embedded_time::{duration::*, rate::*}; use std::convert::TryFrom; use std::mem::size_of; fn duration_vs_core_duration(c: &mut Criterion) { use core::time::Duration; let mut group = c.benchmark_group("Duration Construct/Read"); println!( "embedded_time::Duration size: {} B", size_of::>() ); group.bench_function("embedded_time::Duration", |b| { b.iter(|| { let ms = black_box(123); let duration = Milliseconds::(ms); let count = duration.integer(); let _ = black_box(count); }) }); println!("core::time::Duration size: {} B", size_of::()); group.bench_function("core::time::Duration", |b| { b.iter(|| { let ms = black_box(123); let core_duration = Duration::from_millis(ms); let count = core_duration.as_millis(); let _ = black_box(count); }) }); group.finish(); } fn conversions(c: &mut Criterion) { let mut group = c.benchmark_group("conversions"); let rate = 500_u32.Hz(); group.bench_with_input( BenchmarkId::new("Hertz::to_duration::>()", rate), &rate, |b, &_size| { b.iter(|| rate.to_duration::>()); }, ); let duration = 500_u32.seconds(); group.bench_with_input( BenchmarkId::new("Nanoseconds::try_from::>()", duration), &duration, |b, &_size| { b.iter(|| Nanoseconds::::try_from(duration)); }, ); let duration = 500_u32.milliseconds(); group.bench_with_input( BenchmarkId::new( "Nanoseconds::try_from::>()", duration, ), &duration, |b, &_size| { b.iter(|| Nanoseconds::::try_from(duration)); }, ); let duration = Nanoseconds(500_u64); group.bench_with_input( BenchmarkId::new("Seconds::try_from::>()", duration), &duration, |b, &_size| { b.iter(|| Seconds::::try_from(duration)); }, ); let duration = Nanoseconds(500_u64); group.bench_with_input( BenchmarkId::new( "Seconds::try_from::>() (unwrap)", duration, ), &duration, |b, &_size| { b.iter(|| Seconds::::try_from(duration).unwrap()); }, ); let duration = 500_u32.nanoseconds(); group.bench_with_input( BenchmarkId::new("Seconds::from::>()", duration), &duration, |b, &_size| { b.iter(|| Seconds::::from(duration)); }, ); let duration = 500_u32.nanoseconds(); group.bench_with_input( BenchmarkId::new("Seconds::from::>()", duration), &duration, |b, &_size| { b.iter(|| Seconds::::from(duration)); }, ); let duration = 500_u32.nanoseconds(); group.bench_with_input( BenchmarkId::new("Milliseconds::from::>()", duration), &duration, |b, &_size| { b.iter(|| Milliseconds::::from(duration)); }, ); group.finish(); } criterion_group!(benches, duration_vs_core_duration, conversions); criterion_main!(benches);