Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.