Add option to configure the maximum iterations when iterating automatically

master
Trivernis 4 years ago
parent 86026536ef
commit be72f7d831

@ -1,6 +1,6 @@
[package] [package]
name = "benchlib-rs" name = "benchlib-rs"
version = "0.1.2" version = "0.2.0"
authors = ["Trivernis <trivernis@gmail.com>"] authors = ["Trivernis <trivernis@gmail.com>"]
edition = "2018" edition = "2018"
license-file = "LICENSE" license-file = "LICENSE"

@ -125,15 +125,15 @@ impl Display for DurationDifference {
pub struct Bencher { pub struct Bencher {
measurements: Vec<BenchVec>, measurements: Vec<BenchVec>,
iterations: usize, iterations: usize,
max_auto_iterations: usize,
} }
const MAX_AUTO_ITERATIONS: usize = 10000;
impl Bencher { impl Bencher {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
measurements: Vec::new(), measurements: Vec::new(),
iterations: 100, iterations: 100,
max_auto_iterations: 10000,
} }
} }
@ -145,6 +145,12 @@ impl Bencher {
self self
} }
pub fn set_max_iterations(&mut self, iterations: usize) -> &mut Self {
self.max_auto_iterations = iterations;
self
}
/// Benchmarks a closure a configured number of times. /// Benchmarks a closure a configured number of times.
/// The result will be printed to the console with the given name. /// The result will be printed to the console with the given name.
pub fn bench<T, F: FnMut() -> T>(&mut self, name: &str, mut func: F) -> &mut Self { pub fn bench<T, F: FnMut() -> T>(&mut self, name: &str, mut func: F) -> &mut Self {
@ -158,7 +164,7 @@ impl Bencher {
); );
if self.iterations == 0 { if self.iterations == 0 {
let mut count = 0; let mut count = 0;
while count < MAX_AUTO_ITERATIONS { while count < self.max_auto_iterations {
let start = Instant::now(); let start = Instant::now();
func(); func();
durations.push(start.elapsed()); durations.push(start.elapsed());
@ -167,6 +173,7 @@ impl Bencher {
} }
count += 1; count += 1;
} }
println!("{}After {} iterations{}", style::Faint, count, style::Reset);
} else { } else {
for _ in 0..self.iterations { for _ in 0..self.iterations {
let start = Instant::now(); let start = Instant::now();

@ -25,7 +25,7 @@ mod tests {
fn bench_auto() { fn bench_auto() {
let mut bencher = Bencher::new(); let mut bencher = Bencher::new();
let mut count = 0; let mut count = 0;
bencher.set_iterations(0); bencher.set_iterations(0).set_max_iterations(1000);
bencher.bench("lol", || count += 1); bencher.bench("lol", || count += 1);
assert!(count > 1); assert!(count > 1);
} }

Loading…
Cancel
Save