1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use std::time;

/// A stats handle passed to handlers by [`TotalTimeProfiler`].
#[derive(Debug)]
pub struct TotalTimeStats {
    current: time::Duration,
    total: time::Duration,
}

/// Something that can react to [`TotalTimeProfilerStats`] tracked by [`TotalTimeProfiler`].
pub trait Reporter {
    fn handle_stats(&mut self, stats: &mut TotalTimeStats);
}

impl<F> Reporter for F
where
    F: for<'a> Fn(&'a mut TotalTimeStats),
{
    fn handle_stats(&mut self, stats: &mut TotalTimeStats) {
        (self as &mut F)(stats);
    }
}

/// A simple basic profiler implementation which tracks
/// the accumulative time and calls a handler function
/// with it.
///
/// ## Example
///
/// ```rust
/// use dpc_pariter::{IteratorExt, TotalTimeProfiler};
///
/// dpc_pariter::scope(|scope| {
///     (0..22)
///         .readahead_scoped_profiled(
///             scope,
///             0,
///             TotalTimeProfiler::periodically_millis(10_000, || eprintln!("Blocked on sending")),
///             TotalTimeProfiler::periodically_millis(10_000, || eprintln!("Blocked on receving")),
///         )
///         .for_each(|i| {
///             println!("{i}");
///         })
/// })
/// .expect("thread panicked");
/// ```
#[derive(Debug)]
pub struct TotalTimeProfiler<Reporter> {
    reporter: Reporter,
    start: time::Instant,
    stats: TotalTimeStats,
}

impl<F> TotalTimeProfiler<F>
where
    F: for<'a> Fn(&'a mut TotalTimeStats),
{
    /// Create a [`TotalTimeProfiler`] with any handle
    ///
    /// ## Example
    ///
    /// ```rust
    /// use dpc_pariter::{IteratorExt, TotalTimeProfiler};
    ///
    /// let profiler = TotalTimeProfiler::new(|stats| eprintln!("accumulative sending time so far: {}", stats.total().as_millis()));
    /// ```
    pub fn new(f: F) -> Self {
        Self {
            stats: TotalTimeStats {
                current: time::Duration::default(),
                total: time::Duration::default(),
            },

            start: time::Instant::now(),
            reporter: f,
        }
    }
}

impl<F> TotalTimeProfiler<PeriodicReporter<F>>
where
    F: Fn(),
{
    pub fn periodically_millis(millis: u64, f: F) -> Self {
        Self::periodically(time::Duration::from_millis(millis), f)
    }

    pub fn periodically(period: time::Duration, f: F) -> Self {
        Self {
            stats: TotalTimeStats {
                current: time::Duration::default(),
                total: time::Duration::default(),
            },

            start: time::Instant::now(),
            reporter: PeriodicReporter::new_millis(period, f),
        }
    }
}

/// Reporter calling a function every time the total accumulated time
/// being tracked crosses certain threshold
///
/// Use [`TotalTimeProfiler::periodically_millis`] instead
pub struct PeriodicReporter<F> {
    threshold: time::Duration,
    f: F,
}

impl<F> PeriodicReporter<F>
where
    F: Fn(),
{
    fn new_millis(threshold: time::Duration, f: F) -> Self {
        Self { threshold, f }
    }
}

impl<F> Reporter for PeriodicReporter<F>
where
    F: Fn(),
{
    fn handle_stats(&mut self, stats: &mut TotalTimeStats) {
        stats.periodically(self.threshold, || (self.f)());
    }
}

impl TotalTimeStats {
    fn periodically(&mut self, period: time::Duration, f: impl FnOnce()) {
        if self.total >= period {
            self.total -= period;
            (f)();
        }
    }

    /// Get total accumulated time
    pub fn total(&self) -> time::Duration {
        self.total
    }

    /// Get mutable reference to total accumulated time
    ///
    /// Your free to adjust it.
    pub fn total_mut(&mut self) -> &mut time::Duration {
        &mut self.total
    }
}
impl<Reporter> crate::Profiler for TotalTimeProfiler<Reporter>
where
    Reporter: self::Reporter,
{
    fn start(&mut self) {
        self.start = time::Instant::now();
    }

    fn end(&mut self) {
        self.stats.current = time::Instant::now()
            .duration_since(self.start)
            // Even with absolutely no delay waiting for
            // the other side of the channel a send/recv will take some time.
            // Substract some tiny value to account for it, to prevent
            // rare but spurious and confusing messages.
            .saturating_sub(time::Duration::from_micros(1));

        self.stats.total = self.stats.total.saturating_add(self.stats.current);

        let Self {
            ref mut reporter,
            ref mut stats,
            start: _,
        } = *self;

        reporter.handle_stats(stats);
    }
}