rust-embedded / rust-embedded/linux-embedded-hal
Async-tokio DelayNs implementation inaccurate for delays shorter than a few ms
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 319
- Forks
- 60
- Avg merge
- 12h 31m
- Merged PRs (30d)
- 1
Description
hey fyi
tokio::time::sleepis only good down tomsresolutions, for more granularity we typically need somethingnanosleepor a hot loop, so this implementation won't be accurate for anything less than a couple of ms.having had to solve this a couple of times i suspect a more accurate way to do this would involve using
epoll_waitwith a timeout for> 1usdelays (more accurate kernel timing than sleep is, particularly under the tokio runtime) and a hot loop overInstant::elapsed()for> 1nsdelays (check elapsed and hit the waker every round).possibly combining both into something like:
let now = Instant::now()
loop {
// Grab elapsed at the start of the loop
let elapsed = now.elapsed();
// Break once we exceed the delay duration
if elapsed > duration {
break;
}
// Calculate the remaining sleep time
let remainder = duration - elapsed;
// epoll or spin depending on remainder
if remainder > Duration::from_millis(1) {
epoll_sleep().await;
} else {
spin_sleep().await;
}
}
some folks do more complex things to balance accuracy and cpu use, but, this is fairly straightforward and would be closer to operating as intended.
(it's also good to keep track of elapsed times because there are reasons a sleep might end early, which has caused problems for me in the past)
Originally posted by @ryankurte in https://github.com/rust-embedded/linux-embedded-hal/issues/109#issuecomment-1913732707
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the Async-tokio DelayNs implementation and reviewing how tokio::time::sleep handles sub-millisecond delays. Compare the current behavior with the requested accuracy, then evaluate the proposed epoll_wait and Instant::elapsed approaches; done means delays shorter than a few milliseconds behave accurately without an unbounded CPU-heavy loop.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- embedded-iot, operating-systems
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100