alloc_tracker 0.7.0

Memory allocation 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
//! Per-iteration allocation tracking.

use std::fmt;
use std::sync::{Arc, Mutex};

use crate::report::format_count;
use crate::{ERR_POISONED_LOCK, OperationMetrics, ProcessSpan, ThreadSpan};

/// Aggregates allocation data from repeated measurements of a single operation.
///
/// Multiple operations with the same name can be created concurrently.
///
/// # Examples
///
/// ```no_run
/// use std::hint::black_box;
/// use std::time::Instant;
///
/// use alloc_tracker::{Allocator, Session};
/// use criterion::Criterion;
///
/// #[global_allocator]
/// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
///
/// fn bench(c: &mut Criterion) {
///     let session = Session::new();
///     let string_allocations = session.operation("string_allocations");
///     c.bench_function("string_allocations", |b| {
///         b.iter_custom(|iters| {
///             let start = Instant::now();
///             let _span = string_allocations.measure_process().iterations(iters);
///
///             for _ in 0..iters {
///                 black_box(String::from("Hello, world!"));
///             }
///
///             start.elapsed()
///         });
///     });
/// }
/// ```
#[derive(Debug)]
pub struct Operation {
    metrics: Arc<Mutex<OperationMetrics>>,
}

impl Operation {
    #[must_use]
    pub(crate) fn new(_name: String, operation_data: Arc<Mutex<OperationMetrics>>) -> Self {
        Self {
            metrics: operation_data,
        }
    }

    /// Returns a clone of the operation metrics for use by spans.
    #[must_use]
    pub(crate) fn metrics(&self) -> Arc<Mutex<OperationMetrics>> {
        Arc::clone(&self.metrics)
    }

    /// Begins measuring allocations made by the current thread only.
    ///
    /// Use this for single-threaded operations or when you want to track
    /// per-thread allocation usage.
    ///
    /// You must call [`iterations(n)`](ThreadSpan::iterations) on the returned span
    /// to define how many iterations the measured work covers. This is mandatory.
    /// You may pass `0` to indicate that no work was performed (e.g. on failure).
    ///
    /// The returned span records its measurement when it is dropped.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::hint::black_box;
    /// use std::time::Instant;
    ///
    /// use alloc_tracker::{Allocator, Session};
    /// use criterion::Criterion;
    ///
    /// #[global_allocator]
    /// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
    ///
    /// fn bench(c: &mut Criterion) {
    ///     let session = Session::new();
    ///     let operation = session.operation("thread_work");
    ///     c.bench_function("thread_work", |b| {
    ///         b.iter_custom(|iters| {
    ///             let start = Instant::now();
    ///             let _span = operation.measure_thread().iterations(iters);
    ///
    ///             for _ in 0..iters {
    ///                 black_box(vec![1, 2, 3, 4, 5]);
    ///             }
    ///
    ///             start.elapsed()
    ///         });
    ///     });
    /// }
    /// ```
    pub fn measure_thread(&self) -> ThreadSpan {
        ThreadSpan::new(self)
    }

    /// Begins measuring allocations made by the entire process (all threads).
    ///
    /// Use this to measure total allocations including multi-threaded work.
    ///
    /// You must call [`iterations(n)`](ProcessSpan::iterations) on the returned span
    /// to define how many iterations the measured work covers. This is mandatory.
    /// You may pass `0` to indicate that no work was performed (e.g. on failure).
    ///
    /// The returned span records its measurement when it is dropped.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::hint::black_box;
    /// use std::time::Instant;
    ///
    /// use alloc_tracker::{Allocator, Session};
    /// use criterion::Criterion;
    ///
    /// #[global_allocator]
    /// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
    ///
    /// fn bench(c: &mut Criterion) {
    ///     let session = Session::new();
    ///     let operation = session.operation("process_work");
    ///     c.bench_function("process_work", |b| {
    ///         b.iter_custom(|iters| {
    ///             let start = Instant::now();
    ///             let _span = operation.measure_process().iterations(iters);
    ///
    ///             for _ in 0..iters {
    ///                 black_box(vec![1, 2, 3, 4, 5]);
    ///             }
    ///
    ///             start.elapsed()
    ///         });
    ///     });
    /// }
    /// ```
    pub fn measure_process(&self) -> ProcessSpan {
        ProcessSpan::new(self)
    }

    /// Calculates the mean bytes allocated per iteration.
    ///
    /// Returns 0 if no iterations have been recorded.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn mean(&self) -> u64 {
        let data = self.metrics.lock().expect(ERR_POISONED_LOCK);
        data.mean_bytes()
    }

    /// Returns the total number of iterations recorded.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn total_iterations(&self) -> u64 {
        let data = self.metrics.lock().unwrap();
        data.total_iterations()
    }

    /// Returns the total bytes allocated across all iterations.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn total_bytes_allocated(&self) -> u64 {
        let data = self.metrics.lock().expect(ERR_POISONED_LOCK);
        data.total_bytes_allocated()
    }
}

impl fmt::Display for Operation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The summary shows only the per-iteration slopes, not their intervals.
        let metrics = self.metrics.lock().expect(ERR_POISONED_LOCK);
        match (metrics.bytes_slope(), metrics.allocations_slope()) {
            (Some(bytes), Some(allocations)) => write!(
                f,
                "{} bytes/iter, {} allocations/iter",
                format_count(bytes),
                format_count(allocations),
            ),
            _ => write!(f, "no measurements"),
        }
    }
}

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

    use super::*;
    use crate::Session;
    use crate::allocator::register_fake_allocation;

    fn create_test_operation() -> Operation {
        let session = Session::new().no_stdout().no_file();
        session.operation("test")
    }

    #[test]
    fn operation_new() {
        let operation = create_test_operation();
        assert_eq!(operation.mean(), 0);
        assert_eq!(operation.total_iterations(), 0);
        assert_eq!(operation.total_bytes_allocated(), 0);
    }

    #[test]
    fn operation_add_single() {
        let operation = create_test_operation();

        // Directly test the metrics
        {
            let mut metrics = operation.metrics.lock().unwrap();
            metrics.add_iterations(100, 1, 1);
        }

        assert_eq!(operation.mean(), 100);
        assert_eq!(operation.total_iterations(), 1);
        assert_eq!(operation.total_bytes_allocated(), 100);
    }

    #[test]
    fn operation_add_multiple() {
        let operation = create_test_operation();

        // Directly test the metrics
        {
            let mut metrics = operation.metrics.lock().unwrap();
            metrics.add_iterations(100, 1, 1); // 100 bytes, 1 allocation, 1 iteration
            metrics.add_iterations(200, 2, 1); // 200 bytes, 2 allocations, 1 iteration  
            metrics.add_iterations(300, 3, 1); // 300 bytes, 3 allocations, 1 iteration
        }

        assert_eq!(operation.mean(), 200); // (100 + 200 + 300) / (1 + 1 + 1) = 600 / 3 = 200
        assert_eq!(operation.total_iterations(), 3);
        assert_eq!(operation.total_bytes_allocated(), 600);
    }

    #[test]
    fn operation_add_zero() {
        let operation = create_test_operation();

        // Directly test the metrics
        {
            let mut metrics = operation.metrics.lock().unwrap();
            metrics.add_iterations(0, 0, 1);
            metrics.add_iterations(0, 0, 1);
        }

        assert_eq!(operation.mean(), 0);
        assert_eq!(operation.total_iterations(), 2);
        assert_eq!(operation.total_bytes_allocated(), 0);
    }

    #[test]
    fn operation_span_drop() {
        let operation = create_test_operation();

        {
            let _span = operation.measure_thread().iterations(1);
            // Simulate allocation
            register_fake_allocation(75, 1);
        }

        assert_eq!(operation.mean(), 75);
        assert_eq!(operation.total_iterations(), 1);
        assert_eq!(operation.total_bytes_allocated(), 75);
    }

    #[test]
    fn operation_multiple_spans() {
        let operation = create_test_operation();

        {
            let _span = operation.measure_thread().iterations(1);
            register_fake_allocation(100, 1);
        }

        {
            let _span = operation.measure_thread().iterations(1);
            register_fake_allocation(200, 1);
        }

        assert_eq!(operation.mean(), 150); // (100 + 200) / 2
        assert_eq!(operation.total_iterations(), 2);
        assert_eq!(operation.total_bytes_allocated(), 300);
    }

    #[test]
    fn operation_thread_span_drop() {
        let operation = create_test_operation();

        {
            let _span = operation.measure_thread().iterations(1);
            register_fake_allocation(50, 1);
        }

        assert_eq!(operation.mean(), 50);
        assert_eq!(operation.total_iterations(), 1);
        assert_eq!(operation.total_bytes_allocated(), 50);
    }

    #[test]
    fn operation_mixed_spans() {
        let operation = create_test_operation();

        {
            let _span = operation.measure_thread().iterations(1);
            register_fake_allocation(100, 1);
        }

        {
            let _span = operation.measure_thread().iterations(1);
            register_fake_allocation(200, 1);
        }

        assert_eq!(operation.mean(), 150); // (100 + 200) / 2
        assert_eq!(operation.total_iterations(), 2);
        assert_eq!(operation.total_bytes_allocated(), 300);
    }

    #[test]
    fn operation_thread_span_no_allocation() {
        let operation = create_test_operation();

        {
            let _span = operation.measure_thread().iterations(1);
            // No allocation
        }

        assert_eq!(operation.mean(), 0);
        assert_eq!(operation.total_iterations(), 1);
        assert_eq!(operation.total_bytes_allocated(), 0);
    }

    #[test]
    fn operation_batch_iterations() {
        let operation = create_test_operation();

        {
            let _span = operation.measure_thread().iterations(10);
            // Simulate a 1000 byte allocation that should be divided by 10 iterations
            register_fake_allocation(1000, 10);
        }

        assert_eq!(operation.total_iterations(), 10);
        assert_eq!(operation.total_bytes_allocated(), 1000);
        assert_eq!(operation.mean(), 100); // 1000 / 10
    }

    #[test]
    fn operation_drop_merges_data() {
        let session = Session::new().no_stdout().no_file();

        // Create and use operation
        {
            let operation = session.operation("test");

            // Directly test the metrics
            {
                let mut metrics = operation.metrics.lock().unwrap();
                metrics.add_iterations(100, 2, 5);
            }
            // operation is dropped here, merging data into session
        }

        // Check that session contains the data
        let report = session.to_report();
        assert!(!report.is_empty());

        // Verify the session shows the data was merged. A single span of 100
        // bytes/iter over 5 iterations yields a slope of 100; the two
        // allocations/iter behave the same way. The stdout table shows the slope
        // only (no interval).
        let report = session.to_report();
        let (_, op) = report.operations().next().expect("one operation");
        let stats = op.statistics().expect("operation has spans");
        let session_display = format!("{session}");
        println!("Actual session display: '{session_display}'");
        assert!(
            session_display.contains(&format_count(stats.bytes.slope)),
            "table should show the byte slope: got {session_display}"
        );
        assert!(
            session_display.contains(&format_count(stats.allocations.slope)),
            "table should show the allocation slope: got {session_display}"
        );
    }

    #[test]
    fn multiple_operations_concurrent() {
        let session = Session::new().no_stdout().no_file();

        let op1 = session.operation("test");
        let op2 = session.operation("test");

        // Directly manipulate the metrics
        {
            let mut metrics = op1.metrics.lock().unwrap();
            metrics.add_iterations(100, 1, 2); // 200 bytes, 2 allocations, 2 iterations
            metrics.add_iterations(200, 2, 3); // 600 bytes, 6 allocations, 3 iterations
        }

        // Both operations share the same data immediately since they have the same name
        // Total: 200 + 600 = 800 bytes, 2 + 3 = 5 iterations, mean = 800 / 5 = 160 bytes
        assert_eq!(op1.mean(), 160);
        assert_eq!(op2.mean(), 160);

        // Drop operations
        drop(op1);
        drop(op2);

        // Session should show merged results. The iterations²-weighted
        // through-origin slope over spans (200 bytes / 2 iters) and (600 bytes /
        // 3 iters) is (2·200 + 3·600) / (2² + 3²) = 2200 / 13 ≈ 169.23 bytes/iter,
        // which differs from the pooled mean of 160.
        let session_display = format!("{session}");
        assert!(session_display.contains("169.23"), "got {session_display}");
    }

    static_assertions::assert_impl_all!(Operation: Send, Sync);
    static_assertions::assert_impl_all!(
        Operation: UnwindSafe, RefUnwindSafe
    );

    #[test]
    fn operation_display_shows_robust_per_iteration_estimate() {
        let operation = create_test_operation();

        // Add some data to have a non-zero slope.
        // add_iterations(bytes_delta, count_delta, iterations) means bytes_delta * iterations total bytes.
        {
            let mut metrics = operation.metrics.lock().unwrap();
            metrics.add_iterations(250, 5, 2); // Single span → slope of 250 bytes/iter.
        }

        let display_output = operation.to_string();
        assert!(
            display_output.contains("bytes/iter"),
            "got {display_output}"
        );
        assert!(display_output.contains("250"), "got {display_output}");
    }

    #[test]
    fn operation_display_reports_no_measurements_when_empty() {
        // An operation with no recorded spans has no dispersion statistics, so its
        // Display takes the "no measurements" leg.
        let operation = create_test_operation();
        assert_eq!(operation.to_string(), "no measurements");
    }
}