Skip to main content

datafusion_physical_expr_common/metrics/
elapsed_compute.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::future::Future;
6use std::pin::Pin;
7use std::task::{Context, Poll};
8use std::time::Duration;
9
10use datafusion_common::instant::Instant;
11use pin_project::{pin_project, pinned_drop};
12
13use super::Time;
14
15/// Wraps any [`Future`] and accumulates the wall-clock time spent inside
16/// each [`Future::poll`] call into `elapsed_compute`. Everything that
17/// executes synchronously within a `poll()` scope is measured — including
18/// CPU-bound work, memory copies, and any blocking the future performs
19/// before returning. Time between polls (when the runtime has suspended the
20/// future waiting for I/O, a channel, or a waker) is not measured.
21///
22/// For futures that mix synchronous CPU work with async I/O this gives a
23/// good approximation of CPU time: async I/O causes the future to yield
24/// (`Poll::Pending`), so the I/O latency is excluded automatically.
25///
26/// Note: uses `pin-project` rather than `pin-project-lite` in order to
27/// support `PinnedDrop`, which ensures accumulated time is flushed even
28/// if the future is cancelled (dropped before completion).
29#[pin_project(PinnedDrop)]
30pub struct ElapsedComputeFuture<T> {
31    #[pin]
32    inner: T,
33    /// Local accumulator: elapsed time is collected here during each `poll()`
34    /// and only flushed to `elapsed_compute` on completion (`Poll::Ready`) or
35    /// on drop (`PinnedDrop`). Keeping a separate local `Duration` avoids
36    /// performing an atomic operation on every `poll()` call, at the cost of
37    /// the reported metric value being unavailable until the future finishes.
38    curr: Duration,
39    elapsed_compute: Time,
40}
41
42#[pinned_drop]
43impl<T> PinnedDrop for ElapsedComputeFuture<T> {
44    fn drop(self: Pin<&mut Self>) {
45        if self.curr > Duration::default() {
46            let self_projected = self.project();
47            self_projected
48                .elapsed_compute
49                .add_duration(*self_projected.curr);
50        }
51    }
52}
53
54impl<O, F: Future<Output = O>> Future for ElapsedComputeFuture<F> {
55    type Output = O;
56
57    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
58        let self_projected = self.project();
59        let start = Instant::now();
60        let result = self_projected.inner.poll(cx);
61        *self_projected.curr += start.elapsed();
62        if result.is_ready() {
63            self_projected
64                .elapsed_compute
65                .add_duration(*self_projected.curr);
66            *self_projected.curr = Duration::default();
67        }
68        result
69    }
70}
71
72/// Extension trait that wraps any [`Future`] with [`ElapsedComputeFuture`].
73pub trait ElapsedComputeFutureExt: Future + Sized {
74    /// Wraps this future so that the time spent inside each [`Future::poll`]
75    /// call is accumulated into `elapsed_compute`. See [`ElapsedComputeFuture`]
76    /// for a full description of what is and is not measured.
77    fn with_elapsed_compute(self, elapsed_compute: Time) -> ElapsedComputeFuture<Self>;
78}
79
80impl<O, F: Future<Output = O>> ElapsedComputeFutureExt for F {
81    fn with_elapsed_compute(self, elapsed_compute: Time) -> ElapsedComputeFuture<Self> {
82        ElapsedComputeFuture {
83            inner: self,
84            curr: Duration::default(),
85            elapsed_compute,
86        }
87    }
88}