From f8c1e03ea7870f309bfb3098b34b699ca13a4265 Mon Sep 17 00:00:00 2001 From: YizhePKU Date: Wed, 20 Mar 2024 16:45:33 +0800 Subject: [PATCH] Fix inaccurate sleep duration (#12235) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Improves the accuracy of sleep when the duration is larger than 100ms. Fixes #12223. # User-Facing Changes Sleeping for 150ms should work now. ```nushell ~/nushell> timeit { sleep 150ms } 03/19/2024 10:41:55 AM AM 151ms 344µs 201ns ``` --- crates/nu-command/src/platform/sleep.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/nu-command/src/platform/sleep.rs b/crates/nu-command/src/platform/sleep.rs index 37e23d1caa..e708998b9b 100644 --- a/crates/nu-command/src/platform/sleep.rs +++ b/crates/nu-command/src/platform/sleep.rs @@ -52,16 +52,17 @@ impl Command for Sleep { let total_dur = duration_from_i64(duration) + rest.into_iter().map(duration_from_i64).sum::(); + let deadline = Instant::now() + total_dur; - let ctrlc_ref = &engine_state.ctrlc.clone(); - let start = Instant::now(); loop { - thread::sleep(CTRL_C_CHECK_INTERVAL.min(total_dur)); - if start.elapsed() >= total_dur { + // sleep for 100ms, or until the deadline + let time_until_deadline = deadline.saturating_duration_since(Instant::now()); + if time_until_deadline.is_zero() { break; } - - if nu_utils::ctrl_c::was_pressed(ctrlc_ref) { + thread::sleep(CTRL_C_CHECK_INTERVAL.min(time_until_deadline)); + // exit early if Ctrl+C was pressed + if nu_utils::ctrl_c::was_pressed(&engine_state.ctrlc) { return Err(ShellError::InterruptedByUser { span: Some(call.head), });