diff --git a/src/algorithms/mod.rs b/src/algorithms/mod.rs index 9c4056d..720b957 100644 --- a/src/algorithms/mod.rs +++ b/src/algorithms/mod.rs @@ -1,3 +1,4 @@ +use std::time::Instant; pub mod bogo_sort; pub mod bubble_sort; mod constants; @@ -21,13 +22,16 @@ pub trait Sorter { fn reason(&self) -> Reasons; /// Loops all states and reset state. - fn run(&mut self, array: &mut Vec) { + /// Returns time elapsed (microsseconds). + fn run(&mut self, array: &mut Vec) -> u128 { + let now = Instant::now(); loop { if self.step(array) { break; } } self.reset_state(); + now.elapsed().as_micros() } /// Takes a single step in running the algorithm. diff --git a/src/ui/buttons/mod.rs b/src/ui/buttons/mod.rs index 5e5bd6b..1306a97 100644 --- a/src/ui/buttons/mod.rs +++ b/src/ui/buttons/mod.rs @@ -29,6 +29,17 @@ impl ButtonHandler { app.numbers = util::gen_random_vector(FLOOR, CEIL, VECTOR_SIZE); app.original_numbers = app.numbers.clone(); } + + pub(super) fn handle_benchmark(app: &mut Visualizer) { + app.reset(); + for (i, option) in Algorithms::iter().enumerate() { + app.selected = option; + app.switch_algorithm(); + let time = app.sorter.run(&mut app.numbers); + app.bench_results[i] = time; + println!("{}", app.bench_results[i]); + } + } } #[cfg(test)] diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 1c2cc21..d7452da 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -50,6 +50,8 @@ pub(crate) struct Visualizer<'a> { original_numbers: Vec, state: State, sorter: Box, + bench: bool, + bench_results: Vec, } impl<'a> Default for Visualizer<'a> { @@ -61,6 +63,8 @@ impl<'a> Default for Visualizer<'a> { state: State::Start, original_numbers: numbers, sorter: Box::new(BubbleSort::new()), + bench: false, + bench_results: (0..3).collect::>(), } } } @@ -117,6 +121,17 @@ impl Visualizer<'_> { }); } + fn draw_bench(&self, ui: &mut Ui) { + if self.bench { + ui.horizontal(|ui| { + ui.add_space(400.); + for (i, option) in Algorithms::iter().enumerate() { + ui.label(format!("{option:?} {}", self.bench_results[i])); + } + }); + } + } + /// Create the ComboBox and return true if algorithm selection has been changed. fn handle_combo_box(&mut self, ui: &mut Ui) -> bool { let previous_selection: Algorithms = self.selected; @@ -165,6 +180,10 @@ impl Visualizer<'_> { if ui.add(Button::new("Shuffle")).clicked() { ButtonHandler::handle_shuffle(self); } + if ui.add(Button::new("Benchmark")).clicked() { + ButtonHandler::handle_benchmark(self); + self.bench = true + } } /// If running, take a step and sleep for WAIT_TIME. @@ -226,6 +245,7 @@ impl eframe::App for Visualizer<'_> { ui.add_space(PADDING); self.draw_numbers(ui); + self.draw_bench(ui); }); } }