Skip to content

Commit

Permalink
Interval time elapsed adjustments (#21)
Browse files Browse the repository at this point in the history
* Prototype interval time adjustments

* See how all platforms behave

* Remove interval offset

* Re-work time adjustments

* Finalize test
  • Loading branch information
DoumanAsh committed Mar 23, 2024
1 parent 391e055 commit 879fb97
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ jobs:
runs-on: ${{ matrix.os }}

strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]

Expand Down Expand Up @@ -52,7 +53,7 @@ jobs:
- name: Test with tokio 1.0
if: runner.os != 'Windows'
run: cargo test --features tokio1 -- --nocapture
run: cargo test --features tokio1 --release

- name: Test
run: cargo test --all --features std
Expand Down
12 changes: 10 additions & 2 deletions src/interval.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//!Interval module

use std::time;
use core::task;
use core::future::Future;
use core::{task, time};
use core::pin::Pin;

use crate::timer::Timer;
Expand Down Expand Up @@ -34,6 +35,7 @@ pub struct Interval<T=PlatformTimer> {
timer: T,
///Timer interval, change to this value will be reflected on next restart of timer.
pub interval: time::Duration,
finish_at: time::Instant,
}

impl Interval {
Expand All @@ -49,6 +51,7 @@ impl<T: Timer> Interval<T> {
pub fn new(interval: time::Duration) -> Self {
Self {
timer: T::new(interval),
finish_at: time::Instant::now() + interval,
interval,
}
}
Expand All @@ -61,7 +64,12 @@ impl<T: Timer> Interval<T> {

///Restarts interval
pub fn restart(&mut self) {
let interval = self.interval;
let now = time::Instant::now();

let interval = match now.checked_duration_since(self.finish_at) {
Some(delayed) => self.interval - time::Duration::from_nanos((delayed.as_nanos() % self.interval.as_nanos()) as _),
None => self.interval
};
self.timer.restart(interval);
}

Expand Down
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
//! - `std` - Enables usage of std types (e.g. Error)
#![warn(missing_docs)]

#![no_std]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::style, clippy::needless_lifetimes))]

extern crate alloc;
Expand Down
50 changes: 50 additions & 0 deletions tests/interval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,53 @@ async fn test_interval() {

assert!(diff.as_millis() >= 750 && diff.as_millis() <= 1_250);
}

async fn test_interval_average(num_runs: usize, interval: time::Duration) {
const ACCURACY: time::Duration = time::Duration::from_nanos(133333);

let mut times = Vec::with_capacity(num_runs);

println!("interval={:?}", interval);
let mut timer = async_timer::interval(interval);

for _ in 0..num_runs {
let start = std::time::Instant::now();

timer.wait().await;

// simulate some work, this doesn't have to be consistent
// the timer is the only thing that needs to be consistent
std::thread::sleep(time::Duration::from_millis(1));

// log time, the timer should be waiting less
// to account for the time it took to do the work
times.push(start.elapsed());
}

let total: time::Duration = times.iter().sum();
let average = total / num_runs as u32;

let min = interval - ACCURACY;
let max = interval + ACCURACY;
println!("Check {:?} <= average={:?} <= {:?}", min, average, max);
//Margin of error should be within interval-0.1ms..=interval+0.1ms
assert!(min <= average);
assert!(average <= max);
}

//Windows timers are shite for small duration
//kevent() also behaves badly for some reason
//only linux's timerfd is reliable
#[tokio::test]
#[cfg(feature = "tokio1")]
#[cfg(target_os = "linux")]
async fn test_average_of_small_interval() {
test_interval_average(6000, time::Duration::from_secs_f32(1. / 120.)).await;
}

#[tokio::test]
#[cfg(feature = "tokio1")]
#[cfg(target_os = "linux")]
async fn test_average_of_mid_interval() {
test_interval_average(60, time::Duration::from_secs_f32(135. / 120.)).await;
}

0 comments on commit 879fb97

Please sign in to comment.