all_the_time 0.4.15

Processor time tracking utilities for benchmarks and performance analysis
Documentation
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Processor time tracking reports.

use std::collections::HashMap;
use std::fmt;
use std::time::Duration;

/// Thread-safe processor time tracking report.
///
/// A `Report` contains the captured processor time statistics from a [`Session`](crate::Session)
/// and can be safely sent to other threads for processing. Reports can be merged together
/// and processed independently.
///
/// # Examples
///
/// ```
/// use all_the_time::Session;
///
/// # fn main() {
/// let session = Session::new();
/// let operation = session.operation("test_work");
/// let _span = operation.measure_thread().iterations(100);
/// for _ in 0..100 {
///     std::hint::black_box(42 * 2);
/// }
///
/// let report = session.to_report();
/// report.print_to_stdout();
/// # }
/// ```
///
/// # Merging reports
///
/// ```
/// use std::thread;
///
/// use all_the_time::{Report, Session};
///
/// # fn main() {
/// // Create two separate sessions
/// let session1 = Session::new();
/// let session2 = Session::new();
///
/// // Record some work in each
/// let op1 = session1.operation("work");
/// let _span1 = op1.measure_thread();
/// std::hint::black_box(42);
///
/// let op2 = session2.operation("work");
/// let _span2 = op2.measure_thread();
/// std::hint::black_box(42);
///
/// // Convert to reports and merge
/// let report1 = session1.to_report();
/// let report2 = session2.to_report();
/// let merged = Report::merge(&report1, &report2);
///
/// merged.print_to_stdout();
/// # }
/// ```
#[derive(Clone, Debug, Default)]
pub struct Report {
    operations: HashMap<String, ReportOperation>,
}

/// Processor time statistics for a single operation in a report.
#[derive(Clone, Debug)]
pub struct ReportOperation {
    total_processor_time: Duration,
    total_iterations: u64,
}

impl Report {
    /// Creates an empty report.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn new() -> Self {
        Self {
            operations: HashMap::new(),
        }
    }

    /// Creates a report from shared operation data.
    #[must_use]
    pub(crate) fn from_operation_data(
        operation_data: &HashMap<String, crate::operation_metrics::OperationMetrics>,
    ) -> Self {
        let report_operations = operation_data
            .iter()
            .map(|(name, data)| {
                (
                    name.clone(),
                    ReportOperation {
                        total_processor_time: data.total_processor_time,
                        total_iterations: data.total_iterations,
                    },
                )
            })
            .collect();

        Self {
            operations: report_operations,
        }
    }

    /// Merges two reports into a new report.
    ///
    /// The resulting report contains the combined statistics from both input reports.
    /// Operations with the same name have their statistics combined as if all spans
    /// had been recorded through a single session.
    ///
    /// # Examples
    ///
    /// ```
    /// use all_the_time::{Report, Session};
    ///
    /// # fn main() {
    /// let session1 = Session::new();
    /// let session2 = Session::new();
    ///
    /// // Both sessions record the same operation name
    /// let op1 = session1.operation("common_work");
    /// let _span1 = op1.measure_thread().iterations(5);
    /// for _ in 0..5 {
    ///     std::hint::black_box(42);
    /// }
    ///
    /// let op2 = session2.operation("common_work");
    /// let _span2 = op2.measure_thread().iterations(3);
    /// for _ in 0..3 {
    ///     std::hint::black_box(42);
    /// }
    ///
    /// let report1 = session1.to_report();
    /// let report2 = session2.to_report();
    ///
    /// // Merged report shows combined statistics (8 total iterations)
    /// let merged = Report::merge(&report1, &report2);
    /// # }
    /// ```
    #[must_use]
    pub fn merge(a: &Self, b: &Self) -> Self {
        let mut merged_operations = a.operations.clone();

        for (name, b_op) in &b.operations {
            merged_operations
                .entry(name.clone())
                .and_modify(|a_op| {
                    a_op.total_processor_time = a_op
                        .total_processor_time
                        .checked_add(b_op.total_processor_time)
                        .expect("merging processor times overflows Duration - this indicates an unrealistic scenario");

                    a_op.total_iterations = a_op
                        .total_iterations
                        .checked_add(b_op.total_iterations)
                        .expect("merging iteration counts overflows u64 - this indicates an unrealistic scenario");
                })
                .or_insert_with(|| b_op.clone());
        }

        Self {
            operations: merged_operations,
        }
    }

    /// Prints the processor time statistics to stdout.
    ///
    /// Prints nothing if no operations were captured. This may indicate that the session
    /// was part of a "list available benchmarks" probe run instead of some real activity,
    /// in which case printing anything might violate the output protocol the tool is speaking.
    #[cfg_attr(test, mutants::skip)] // Too difficult to test stdout output reliably - manually tested.
    pub fn print_to_stdout(&self) {
        if self.is_empty() {
            return;
        }
        println!("{self}");
    }

    /// Whether there is any recorded activity in this report.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.operations.is_empty() || self.operations.values().all(|op| op.total_iterations == 0)
    }

    /// Returns an iterator over the operation names and their statistics.
    ///
    /// This allows programmatic access to the same data that would be printed by
    /// [`print_to_stdout()`](Self::print_to_stdout).
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use all_the_time::Session;
    ///
    /// # fn main() {
    /// let session = Session::new();
    /// let operation = session.operation("test_work");
    /// let _span = operation.measure_thread().iterations(100);
    /// for _ in 0..100 {
    ///     std::hint::black_box(42 * 2);
    /// }
    ///
    /// let report = session.to_report();
    /// for (name, op) in report.operations() {
    ///     println!(
    ///         "Operation '{}' had {} iterations",
    ///         name,
    ///         op.total_iterations()
    ///     );
    ///     println!("Mean time per iteration: {:?}", op.mean());
    ///     println!("Total time: {:?}", op.total_processor_time());
    /// }
    /// # }
    /// ```
    pub fn operations(&self) -> impl Iterator<Item = (&str, &ReportOperation)> {
        self.operations.iter().map(|(name, op)| (name.as_str(), op))
    }
}

impl ReportOperation {
    /// Returns the total processor time across all iterations for this operation.
    #[must_use]
    pub fn total_processor_time(&self) -> Duration {
        self.total_processor_time
    }

    /// Returns the total number of iterations recorded for this operation.
    #[must_use]
    pub fn total_iterations(&self) -> u64 {
        self.total_iterations
    }

    /// Calculates the mean processor time per iteration.
    #[must_use]
    pub fn mean(&self) -> Duration {
        if self.total_iterations == 0 {
            Duration::ZERO
        } else {
            Duration::from_nanos(
                self.total_processor_time
                    .as_nanos()
                    .checked_div(u128::from(self.total_iterations))
                    .expect("guarded by if condition")
                    .try_into()
                    .expect("all realistic values fit in u64"),
            )
        }
    }
}

impl fmt::Display for ReportOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} (mean)", self.mean())
    }
}

#[cfg_attr(coverage_nightly, coverage(off))] // Too annoying to test every question mark operator.
impl fmt::Display for Report {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.operations.values().all(|op| op.total_iterations == 0) {
            writeln!(f, "No processor time statistics captured.")?;
        } else {
            writeln!(f, "Processor time statistics:")?;
            writeln!(f)?;

            // Sort operations by name for consistent output
            let mut sorted_ops: Vec<_> = self.operations.iter().collect();
            sorted_ops.sort_by_key(|(name, _)| *name);

            // Calculate the maximum width needed for the operation name column
            let max_name_width = sorted_ops
                .iter()
                .map(|(name, _)| name.len())
                .max()
                .unwrap_or(0)
                .max("Operation".len());

            // Calculate the maximum width needed for the mean column
            let max_mean_width = sorted_ops
                .iter()
                .map(|(_, operation)| format!("{:?}", operation.mean()).len())
                .max()
                .unwrap_or(0)
                .max("Mean".len());

            // Print table header
            writeln!(
                f,
                "| {:<name_width$} | {:>mean_width$} |",
                "Operation",
                "Mean",
                name_width = max_name_width,
                mean_width = max_mean_width
            )?;
            let separator_name_width = max_name_width
                .checked_add(2)
                .expect("operation name width fits in memory, adding 2 cannot overflow");
            let separator_mean_width = max_mean_width
                .checked_add(2)
                .expect("mean width fits in memory, adding 2 cannot overflow");
            writeln!(
                f,
                "|{:-<name_width$}|{:-<mean_width$}|",
                "",
                "",
                name_width = separator_name_width,
                mean_width = separator_mean_width
            )?;

            // Print table rows
            for (name, operation) in sorted_ops {
                writeln!(
                    f,
                    "| {:<name_width$} | {:>mean_width$} |",
                    name,
                    format!("{:?}", operation.mean()),
                    name_width = max_name_width,
                    mean_width = max_mean_width
                )?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::panic::RefUnwindSafe;
    use std::panic::UnwindSafe;

    use super::*;
    use crate::Session;

    fn create_test_session() -> Session {
        use crate::pal::{FakePlatform, PlatformFacade};
        let fake_platform = FakePlatform::new();
        let platform_facade = PlatformFacade::fake(fake_platform);
        Session::with_platform(platform_facade)
    }

    #[test]
    fn new_report_is_empty() {
        let report = Report::new();
        assert!(report.is_empty());
    }

    #[test]
    fn report_from_empty_session_is_empty() {
        let session = create_test_session();
        let report = session.to_report();
        assert!(report.is_empty());
    }

    #[test]
    fn report_from_session_with_operations_is_not_empty() {
        let session = create_test_session();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread();
        } // Span drops here, releasing the mutable borrow

        let report = session.to_report();
        assert!(!report.is_empty());
    }

    #[test]
    fn merge_empty_reports() {
        let report1 = Report::new();
        let report2 = Report::new();
        let merged = Report::merge(&report1, &report2);
        assert!(merged.is_empty());
    }

    #[test]
    fn merge_empty_with_non_empty() {
        let session = create_test_session();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread();
        } // Span drops here

        let report1 = Report::new();
        let report2 = session.to_report();

        let merged1 = Report::merge(&report1, &report2);
        let merged2 = Report::merge(&report2, &report1);

        assert!(!merged1.is_empty());
        assert!(!merged2.is_empty());
    }

    #[test]
    fn merge_different_operations() {
        let session1 = create_test_session();
        let session2 = create_test_session();

        {
            let op1 = session1.operation("test1");
            let _span1 = op1.measure_thread();
        } // Span drops here

        {
            let op2 = session2.operation("test2");
            let _span2 = op2.measure_thread();
        } // Span drops here

        let report1 = session1.to_report();
        let report2 = session2.to_report();
        let merged = Report::merge(&report1, &report2);

        assert_eq!(merged.operations.len(), 2);
        assert!(merged.operations.contains_key("test1"));
        assert!(merged.operations.contains_key("test2"));
    }

    #[test]
    fn merge_same_operations() {
        let session1 = create_test_session();
        let session2 = create_test_session();

        {
            let op1 = session1.operation("test");
            let _span1 = op1.measure_thread().iterations(5);
        } // Span drops here

        {
            let op2 = session2.operation("test");
            let _span2 = op2.measure_thread().iterations(3);
        } // Span drops here

        let report1 = session1.to_report();
        let report2 = session2.to_report();
        let merged = Report::merge(&report1, &report2);

        assert_eq!(merged.operations.len(), 1);
        let merged_op = merged.operations.get("test").unwrap();
        assert_eq!(merged_op.total_iterations, 8); // 5 + 3
    }

    #[test]
    fn report_clone() {
        let session = create_test_session();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread();
        } // Span drops here

        let report1 = session.to_report();
        let report2 = report1.clone();

        assert_eq!(report1.operations.len(), report2.operations.len());
    }

    #[test]
    fn report_mean_with_fake_platform() {
        use crate::pal::{FakePlatform, PlatformFacade};

        // Create fake platform that we can modify during the test
        let fake_platform = FakePlatform::new();
        let platform_facade = PlatformFacade::fake(fake_platform.clone());
        let session = Session::with_platform(platform_facade);

        // First operation: start at 10ms, end at 50ms = 40ms duration
        fake_platform.set_thread_time(Duration::from_millis(10));
        {
            let operation = session.operation("test_operation");
            let _span = operation.measure_thread().iterations(4);
            // Progress time during the operation to demonstrate time passing
            fake_platform.set_thread_time(Duration::from_millis(50));
        } // Operation is dropped here, recording 40ms total for 4 iterations

        // Second operation: start at 50ms, end at 90ms = 40ms duration
        {
            let operation = session.operation("test_operation");
            let _span = operation.measure_thread().iterations(2);
            // Progress time during this operation too
            fake_platform.set_thread_time(Duration::from_millis(90));
        } // Operation is dropped here, recording another 40ms total for 2 iterations

        let report = session.to_report();
        let operations: Vec<_> = report.operations().collect();
        assert_eq!(operations.len(), 1);

        let (_name, op) = operations.first().unwrap();

        // Verify the operation recorded meaningful durations
        // The same operation name means they merge:
        // First operation: 40ms total / 4 iterations
        // Second operation: 40ms total / 2 iterations
        // Combined: (40ms + 40ms) total / (4 + 2) iterations = 80ms / 6 = ~13.33ms mean
        let expected_mean = Duration::from_nanos(13_333_333); // 80ms / 6 iterations
        assert_eq!(op.mean(), expected_mean);

        // Verify total duration and iteration count
        assert_eq!(op.total_processor_time(), Duration::from_millis(80));
        assert_eq!(op.total_iterations(), 6);
    }

    // Static assertions for thread safety.
    static_assertions::assert_impl_all!(Report: Send, Sync);
    static_assertions::assert_impl_all!(ReportOperation: Send, Sync);

    // Static assertions for unwind safety.
    static_assertions::assert_impl_all!(Report: UnwindSafe, RefUnwindSafe);
    static_assertions::assert_impl_all!(
        ReportOperation: UnwindSafe, RefUnwindSafe
    );

    #[test]
    fn report_operation_display_shows_mean() {
        use crate::pal::{FakePlatform, PlatformFacade};

        let fake_platform = FakePlatform::new();
        let platform_facade = PlatformFacade::fake(fake_platform.clone());
        let session = Session::with_platform(platform_facade);

        // Set up timing: 100ms total for 2 iterations = 50ms mean
        fake_platform.set_thread_time(Duration::from_millis(0));
        {
            let operation = session.operation("test_op");
            let _span = operation.measure_thread().iterations(2);
            fake_platform.set_thread_time(Duration::from_millis(100));
        }

        let report = session.to_report();
        let (_name, op) = report.operations().next().unwrap();

        let display = op.to_string();
        assert!(display.contains("mean"), "Display should mention 'mean'");
        // Duration debug format varies, but should contain '50' for 50ms
        assert!(
            display.contains("50"),
            "Display should show the mean duration containing '50' (for 50ms): got {display}"
        );
    }
}