Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created April 9, 2019 18:50
Show Gist options
  • Save rust-play/b41368bb2f2af40aadc28b97ef924c9d to your computer and use it in GitHub Desktop.
Save rust-play/b41368bb2f2af40aadc28b97ef924c9d to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[macro_use]
extern crate criterion;
// Don't run this on Playground!
// Run it locally using `cargo bench`
use criterion::Criterion;
use ndarray::Array1;
fn midpoints(n: u32, a: f32, b: f32) -> Array1<f32> {
assert!(a < b);
assert!(n > 0);
let length = (b - a) / (n as f32);
let start = a + length;
let end = b + length;
Array1::range(start, end, length)
}
fn rectangle_rule<F>(n: u32, a: f32, b: f32, f: F) -> f32
where
F: FnMut(&f32) -> f32
{
let points = midpoints(n, a, b);
let f_values = points.map(f);
let length = (b - a) / (n as f32);
let integral_estimate = f_values.sum() * length;
integral_estimate
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function(
"rectangle",
move |b| b.iter(
|| rectangle_rule(50000, 0., 1., |x| x.sin())
)
);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment