From dda277fd2d58022cb64fdbe767ec181d8ee687d5 Mon Sep 17 00:00:00 2001 From: BD103 <59022059+BD103@users.noreply.github.com> Date: Tue, 13 Feb 2024 13:24:29 -0500 Subject: [PATCH 1/2] feat: add spin_loop hint to async_computer example --- examples/async_tasks/async_compute.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/async_tasks/async_compute.rs b/examples/async_tasks/async_compute.rs index 60d2eba88aa75..afa85c1975904 100644 --- a/examples/async_tasks/async_compute.rs +++ b/examples/async_tasks/async_compute.rs @@ -65,6 +65,7 @@ fn spawn_tasks(mut commands: Commands) { while start_time.elapsed() < duration { // Spinning for 'duration', simulating doing hard // compute work generating translation coords! + std::hint::spin_loop(); } // Such hard work, all done! From 74b1f1fe8d36728c72382b338f477b298cc56c61 Mon Sep 17 00:00:00 2001 From: BD103 <59022059+BD103@users.noreply.github.com> Date: Tue, 13 Feb 2024 18:02:04 -0500 Subject: [PATCH 2/2] feat: convert busy loop to thread::sleep --- examples/async_tasks/async_compute.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/examples/async_tasks/async_compute.rs b/examples/async_tasks/async_compute.rs index afa85c1975904..134373bc36c97 100644 --- a/examples/async_tasks/async_compute.rs +++ b/examples/async_tasks/async_compute.rs @@ -7,7 +7,7 @@ use bevy::{ tasks::{block_on, futures_lite::future, AsyncComputeTaskPool, Task}, }; use rand::Rng; -use std::time::{Duration, Instant}; +use std::{thread, time::Duration}; fn main() { App::new() @@ -60,13 +60,11 @@ fn spawn_tasks(mut commands: Commands) { let entity = commands.spawn_empty().id(); let task = thread_pool.spawn(async move { let mut rng = rand::thread_rng(); - let start_time = Instant::now(); + let duration = Duration::from_secs_f32(rng.gen_range(0.05..0.2)); - while start_time.elapsed() < duration { - // Spinning for 'duration', simulating doing hard - // compute work generating translation coords! - std::hint::spin_loop(); - } + + // Pretend this is a time-intensive function. :) + thread::sleep(duration); // Such hard work, all done! let transform = Transform::from_xyz(x as f32, y as f32, z as f32);