Skip to content

Commit

Permalink
Add parallel query example
Browse files Browse the repository at this point in the history
  • Loading branch information
GrantMoyer committed Sep 1, 2020
1 parent 33a9c88 commit da74491
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,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"
Expand Down
44 changes: 44 additions & 0 deletions examples/ecs/parallel_query.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use bevy::{prelude::*, tasks::prelude::*};
use std::{
sync::{atomic, atomic::AtomicUsize},
thread,
time::{Duration, Instant},
};

fn spawn_system(mut commands: Commands) {
for i in 0..16usize {
commands.spawn((i,));
}
}

fn square_system(pool: Res<ComputeTaskPool>, mut nums: Query<&mut usize>) {
let i = AtomicUsize::new(0);
nums.iter().iter_batched(1).for_each(&pool, |mut n| {
println!(
"Processing entity {}",
i.fetch_add(1, atomic::Ordering::Relaxed)
);
thread::sleep(Duration::from_secs(1));
*n = *n * *n;
});
}

fn print_threads_system(pool: Res<ComputeTaskPool>) {
println!("Using {} threads in compute pool", pool.thread_num());
}

fn print_system(num: &usize) {
print!("{} ", num);
}

fn main() {
let t0 = Instant::now();
App::build()
.add_startup_system(spawn_system.system())
.add_startup_system(print_threads_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());
}

0 comments on commit da74491

Please sign in to comment.