diff --git a/examples/benchmark.rs b/examples/benchmark.rs index ae15e3a..c06152f 100644 --- a/examples/benchmark.rs +++ b/examples/benchmark.rs @@ -1,54 +1,49 @@ -use std::{ - collections::{HashMap, HashSet}, - sync::{Arc, Mutex}, -}; +use std::{sync::mpsc, sync::Arc, thread}; use osui::prelude::*; pub fn main() { let engine = Arc::new(Benchmark::new(Console::new())); - let benchmark_result = Arc::new(Mutex::new(HashMap::new())); - let benchmark_running = Arc::new(Mutex::new(HashSet::new())); - for items in 0..1000 { - let engine = engine.clone(); - let benchmark_result = benchmark_result.clone(); - let benchmark_running = benchmark_running.clone(); + let (tx, rx) = mpsc::channel(); - std::thread::spawn(move || { - benchmark_running.lock().unwrap().insert(items); + let max_threads = 128; + let mut handles = vec![]; - let res = engine - .run(move |cx| { - rsx! { - for _ in (0..items) { - "Hello, world!" + for chunk in (0..500).collect::>().chunks(max_threads) { + for &items in chunk { + let engine = engine.clone(); + let tx = tx.clone(); + + let handle = thread::spawn(move || { + let res = engine + .run(move |cx| { + rsx! { + for _ in (0..items) { + "Hello, world!" + } } - } - .view(cx.clone()) - }) - .expect("Failed to run engine"); + .view(cx.clone()) + }) + .expect("Failed to run engine"); - benchmark_result.lock().unwrap().insert(items, res); - benchmark_running.lock().unwrap().remove(&items); - }); + tx.send((items, res)).expect("Failed to send result"); + }); + + handles.push(handle); + } + + for handle in handles.drain(..) { + handle.join().expect("Thread panicked"); + } } - while !benchmark_running.lock().unwrap().is_empty() { - std::thread::sleep(std::time::Duration::from_millis(500)); + drop(tx); + + let mut results: Vec<(usize, BenchmarkResult)> = rx.iter().collect(); + results.sort_by_key(|(items, _)| *items); + + for (items, bench) in results { + println!("Results for {items} items:\n{bench}"); } - - let r = benchmark_result.lock().unwrap().clone(); - let mut bench_results = r.iter().collect::>(); - - bench_results.sort_by_key(|(_, bench)| bench.total_render); - - println!( - "{}", - bench_results - .iter() - .map(|(key, bench)| format!("Results for {key} items:\n{bench}")) - .collect::>() - .join("\n") - ); }