From 808a242a1847886d77b3657e05818c58d7a02936 Mon Sep 17 00:00:00 2001 From: Grant Moyer Date: Sat, 22 Aug 2020 19:03:33 -0400 Subject: [PATCH] Add parallel iteration example --- Cargo.toml | 4 ++++ examples/ecs/parallel_query.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 examples/ecs/parallel_query.rs diff --git a/Cargo.toml b/Cargo.toml index cb5fbf4d5478a0..71f14d3ffd921d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -159,6 +159,10 @@ path = "examples/ecs/startup_system.rs" name = "ecs_guide" path = "examples/ecs/ecs_guide.rs" +[[example]] +name = "parallel_query" +path = "examples/ecs/parallel_query.rs" + [[example]] name = "breakout" path = "examples/game/breakout.rs" diff --git a/examples/ecs/parallel_query.rs b/examples/ecs/parallel_query.rs new file mode 100644 index 00000000000000..f5cc92bb0c5f66 --- /dev/null +++ b/examples/ecs/parallel_query.rs @@ -0,0 +1,33 @@ +use bevy::{ecs::rayon::prelude::*, prelude::*}; +use std::{ + thread, + time::{Duration, Instant}, +}; + +fn spawn_system(mut commands: Commands) { + for i in 0..16usize { + commands.spawn((i,)); + } +} + +fn square_system(mut nums: Query<&mut usize>) { + nums.iter().into_par_iter().for_each(|mut n| { + thread::sleep(Duration::from_secs(1)); + *n = *n * *n; + }); +} + +fn print_system(num: &usize) { + print!("{} ", num); +} + +fn main() { + let t0 = Instant::now(); + App::build() + .add_startup_system(spawn_system.system()) + .add_system(square_system.system()) + .add_system(print_system.system()) + .run(); + let t1 = Instant::now(); + println!("\nTook {:.3}s", (t1 - t0).as_secs_f32()); +}