Created
October 31, 2023 17:21
-
-
Save westonpace/e919fc5716c78dde929ec572b87bb465 to your computer and use it in GitHub Desktop.
dyn vs impl rust bench
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use criterion::{criterion_group, criterion_main, Criterion}; | |
use pprof::criterion::{Output, PProfProfiler}; | |
// Type your code here, or load an example. | |
pub fn square<'a, I: IntoIterator<Item = &'a i32>>( | |
vals: I, | |
) -> impl Iterator<Item = (&'a i32, i32)> { | |
vals.into_iter().map(|v| (v, v * v)) | |
} | |
pub fn sum_squared<'a, I: IntoIterator<Item = &'a i32>>(vals: I) -> i32 { | |
square(vals).map(|(_, sq)| sq).sum() | |
} | |
pub fn square_dyn<'a, I: IntoIterator<Item = &'a i32> + 'a>( | |
vals: I, | |
) -> Box<dyn Iterator<Item = (&'a i32, i32)> + 'a> { | |
Box::new(vals.into_iter().map(|v| (v, v * v))) | |
} | |
pub fn sum_squared_dyn<'a, I: IntoIterator<Item = &'a i32> + 'a>(vals: I) -> i32 { | |
square_dyn(vals).map(|(_, sq)| sq).sum() | |
} | |
const NUM_ROWS: i32 = 4096; | |
pub fn criterion_benchmark(c: &mut Criterion) { | |
let data: Vec<i32> = (0..NUM_ROWS).collect(); | |
c.bench_function("impl", |b| b.iter(|| sum_squared(&data))); | |
c.bench_function("dyn", |b| b.iter(|| sum_squared_dyn(&data))); | |
} | |
criterion_group! { | |
name = benches; | |
config = Criterion::default().with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); | |
targets = criterion_benchmark | |
} | |
criterion_main!(benches); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment