Skip to content

Introduce Timed to track how long a future is alive for #7274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion tokio-util/src/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

use std::future::Future;
use std::time::Duration;
use tokio::time::Timeout;
use tokio::time::{Timed, Timeout};

mod wheel;

Expand Down Expand Up @@ -43,6 +43,36 @@ pub trait FutureExt: Future {
{
tokio::time::timeout(timeout, self)
}

/// A wrapper around [`tokio::time::Timed`], with the advantage that it is easier to write
/// fluent call chains.
///
/// # Examples
///
/// ```rust
/// /// use tokio::{sync::oneshot, time::Duration};
/// use tokio_util::time::FutureExt;
/// use tokio::sync::oneshot;
/// use tokio::time::Duration;
///
/// # async fn dox() {
/// let (tx, rx) = oneshot::channel::<()>();
///
/// tokio::task::spawn(async move {
/// tokio::time::sleep(Duration::from_millis(5)).await;
/// tx.send(()).unwrap();
/// });
///
/// let (res, duration) = rx.timed().await;
/// println!("Received {res:?} after {duration:?}");
/// # }
/// ```
fn timed(self) -> Timed<Self>
where
Self: Sized,
{
tokio::time::timed(self)
}
}

impl<T: Future + ?Sized> FutureExt for T {}
Expand Down
3 changes: 3 additions & 0 deletions tokio/src/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ pub use interval::{interval, interval_at, Interval, MissedTickBehavior};
mod sleep;
pub use sleep::{sleep, sleep_until, Sleep};

mod timed;
pub use timed::{timed, Timed};

mod timeout;
#[doc(inline)]
pub use timeout::{timeout, timeout_at, Timeout};
Expand Down
80 changes: 80 additions & 0 deletions tokio/src/time/timed.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use std::{
future::{Future, IntoFuture},
pin::Pin,
task::Poll,
};

use pin_project_lite::pin_project;

use crate::time::Instant;

/// Constructs a `Timed` future that wraps an underlying `Future`. The `Timed` future will return
/// the result of the underlying future as well as the duration the `Timed` was constructed for.
///
/// /// # Examples
///
/// Track how long we waited on a oneshot rx.
///
/// ```rust
/// use tokio::time::timed;
/// use tokio::sync::oneshot;
///
/// # async fn dox() {
/// let (tx, rx) = oneshot::channel();
/// # tx.send(()).unwrap();
///
/// // Wrap the future with a `Timed` to see how long we were at this step.
/// let (_received, duration) = timed(rx).await;
/// println!("Received a value after waiting {duration:?}");
/// # }
/// ```
pub fn timed<F>(future: F) -> Timed<F::IntoFuture>
where
F: IntoFuture,
{
Timed {
inner: future.into_future(),
start: Instant::now(),
}
}

pin_project! {
/// A helper future that wraps an inner future to also return how long the `Timed` was constructed.
/// If constructed right before an await, it will give accurate timing information on the
/// underlying future.
///
/// # Examples
///
/// Time a future.
///
/// ```
/// use tokio::time::timed;
///
/// async fn i_wish_i_knew_how_long_something_took_in_here() {
/// let (_, elapsed) = timed(async {
/// // do async work
/// }).await;
/// }
/// ```
pub struct Timed<T> {
#[pin]
inner: T,
start: Instant,
}
}

impl<T> Future for Timed<T>
where
T: Future,
{
type Output = (T::Output, std::time::Duration);

fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
let this = self.project();
if let Poll::Ready(inner) = this.inner.poll(cx) {
Poll::Ready((inner, this.start.elapsed()))
} else {
Poll::Pending
}
}
}
20 changes: 20 additions & 0 deletions tokio/tests/time_timed.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use tokio::time::{self, timed, Duration};

#[tokio::test(start_paused = true)]
async fn accuracy() {
let durations = vec![
Duration::from_millis(50),
Duration::from_millis(100),
Duration::from_millis(200),
];
for expected in durations {
let ((), elapsed) = timed(time::sleep(expected)).await;
assert_eq!(elapsed, expected);
}
}

#[tokio::test(start_paused = true)]
async fn immediate_future() {
let ((), elapsed) = timed(std::future::ready(())).await;
assert_eq!(elapsed, Duration::from_millis(0));
}
Loading