Fix inaccurate sleep duration (#12235)

# 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
```
This commit is contained in:
YizhePKU 2024-03-20 16:45:33 +08:00 committed by GitHub
parent f56070cbcd
commit f8c1e03ea7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -52,16 +52,17 @@ impl Command for Sleep {
let total_dur =
duration_from_i64(duration) + rest.into_iter().map(duration_from_i64).sum::<Duration>();
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),
});