par_bench 0.2.33

Mechanisms for multithreaded benchmarking, designed for integration with Criterion or a similar benchmark framework
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! Extension trait for combined resource usage tracking in benchmark runs.
//!
//! This module provides an extension trait that adds combined allocation and processor time
//! tracking capabilities to the `Run` builder types when either the `alloc_tracker` or
//! `all_the_time` features are enabled.

/// Extension trait for combined resource usage tracking in benchmark runs.
///
/// This trait adds the `measure_resource_usage` method to `Run` builder types, providing
/// a convenient way to track multiple types of resource usage during benchmark execution.
/// The available measurement types depend on which features are enabled.
///
/// # Examples
///
/// ```
/// use all_the_time::Session as TimeSession;
/// # #[cfg(all(feature = "alloc_tracker", feature = "all_the_time"))]
/// # fn example() {
/// use alloc_tracker::{Allocator, Session as AllocSession};
/// use many_cpus::SystemHardware;
/// use par_bench::{ResourceUsageExt, Run, ThreadPool};
///
/// #[global_allocator]
/// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
///
/// let allocs = AllocSession::new();
/// let processor_time = TimeSession::new();
/// let mut pool = ThreadPool::new(&SystemHardware::current().processors());
///
/// let run = Run::new()
///     .measure_resource_usage("my_operation", |measure| {
///         measure.allocs(&allocs).processor_time(&processor_time)
///     })
///     .iter(|_| {
///         let _data = vec![1, 2, 3, 4, 5]; // This allocates memory
///
///         // Perform processor-intensive work
///         let mut sum = 0_u64;
///         for i in 0_u64..1000 {
///             sum = sum.wrapping_add(i.wrapping_mul(i));
///         }
///         std::hint::black_box(sum);
///     });
///
/// let results = run.execute_on(&mut pool, 1000);
///
/// // Access the combined resource usage data
/// for output in results.measure_outputs() {
///     println!("Resource usage data collected");
/// }
/// # }
/// # #[cfg(all(feature = "alloc_tracker", feature = "all_the_time"))]
/// # example();
/// ```
pub trait ResourceUsageExt<'a, ThreadState> {
    /// The type returned when resource usage tracking is configured.
    type Output;

    /// Configures resource usage tracking for the benchmark run.
    ///
    /// This method creates a measurement wrapper that tracks various types of resource usage
    /// based on the enabled features and the configuration provided in the callback.
    ///
    /// The callback receives a [`ResourceUsageMeasureBuilder`] that can be used to configure
    /// which types of measurements should be taken during the benchmark run.
    ///
    /// # Parameters
    ///
    /// * `operation_name` - The name to assign to this operation in all tracking results
    /// * `configure` - A callback that configures which resource measurements to track
    ///
    /// # Examples
    ///
    /// With allocation tracking only:
    /// ```
    /// # #[cfg(feature = "alloc_tracker")]
    /// # fn example() {
    /// use alloc_tracker::{Allocator, Session};
    /// use many_cpus::SystemHardware;
    /// use par_bench::{ResourceUsageExt, Run, ThreadPool};
    ///
    /// #[global_allocator]
    /// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
    ///
    /// let allocs = Session::new();
    /// let mut pool = ThreadPool::new(&SystemHardware::current().processors());
    ///
    /// let run = Run::new()
    ///     .measure_resource_usage("vector_creation", |measure| measure.allocs(&allocs))
    ///     .iter(|_| {
    ///         let _data = vec![1, 2, 3, 4, 5];
    ///     });
    ///
    /// let results = run.execute_on(&mut pool, 100);
    /// # }
    /// # #[cfg(feature = "alloc_tracker")]
    /// # example();
    /// ```
    ///
    /// With processor time tracking only:
    /// ```
    /// # #[cfg(feature = "all_the_time")]
    /// # fn example() {
    /// use all_the_time::Session;
    /// use many_cpus::SystemHardware;
    /// use par_bench::{ResourceUsageExt, Run, ThreadPool};
    ///
    /// let processor_time = Session::new();
    /// let mut pool = ThreadPool::new(&SystemHardware::current().processors());
    ///
    /// let run = Run::new()
    ///     .measure_resource_usage("cpu_work", |measure| {
    ///         measure.processor_time(&processor_time)
    ///     })
    ///     .iter(|_| {
    ///         let mut sum = 0_u64;
    ///         for i in 0_u64..1000 {
    ///             sum = sum.wrapping_add(i);
    ///         }
    ///         std::hint::black_box(sum);
    ///     });
    ///
    /// let results = run.execute_on(&mut pool, 100);
    /// # }
    /// # #[cfg(feature = "all_the_time")]
    /// # example();
    /// ```
    fn measure_resource_usage<F>(self, operation_name: &'a str, configure: F) -> Self::Output
    where
        F: FnOnce(ResourceUsageMeasureBuilder<'a>) -> ResourceUsageMeasureBuilder<'a>;
}

/// Builder for configuring resource usage measurements.
///
/// This builder allows you to configure which types of resource usage should be tracked
/// during benchmark execution. The available methods depend on which features are enabled.
#[derive(Clone, Debug)]
pub struct ResourceUsageMeasureBuilder<'a> {
    #[cfg(feature = "alloc_tracker")]
    alloc_session: Option<&'a alloc_tracker::Session>,

    #[cfg(feature = "all_the_time")]
    time_session: Option<&'a all_the_time::Session>,
}

impl<'a> ResourceUsageMeasureBuilder<'a> {
    /// Creates a new empty resource usage measure builder.
    #[must_use]
    pub(crate) fn new() -> Self {
        Self {
            #[cfg(feature = "alloc_tracker")]
            alloc_session: None,

            #[cfg(feature = "all_the_time")]
            time_session: None,
        }
    }

    /// Configures allocation tracking for the benchmark run.
    ///
    /// This method is only available when the `alloc_tracker` feature is enabled.
    ///
    /// # Parameters
    ///
    /// * `session` - The allocation tracking session to use
    #[cfg(feature = "alloc_tracker")]
    #[must_use]
    pub fn allocs(mut self, session: &'a alloc_tracker::Session) -> Self {
        self.alloc_session = Some(session);
        self
    }

    /// Configures processor time tracking for the benchmark run.
    ///
    /// This method is only available when the `all_the_time` feature is enabled.
    ///
    /// # Parameters
    ///
    /// * `session` - The processor time tracking session to use
    #[cfg(feature = "all_the_time")]
    #[must_use]
    pub fn processor_time(mut self, session: &'a all_the_time::Session) -> Self {
        self.time_session = Some(session);
        self
    }
}

/// Combined resource usage measurement output.
///
/// This struct contains the measurement results from all configured resource usage tracking.
/// The available methods depend on which features are enabled and which measurements were
/// configured during the benchmark run.
#[derive(Debug)]
pub struct ResourceUsageOutput {
    #[cfg(feature = "alloc_tracker")]
    alloc_report: Option<alloc_tracker::Report>,

    #[cfg(feature = "all_the_time")]
    time_report: Option<all_the_time::Report>,
}

impl ResourceUsageOutput {
    /// Creates a new resource usage output with the specified reports.
    #[must_use]
    pub(crate) fn new(
        #[cfg(feature = "alloc_tracker")] alloc_report: Option<alloc_tracker::Report>,
        #[cfg(feature = "all_the_time")] time_report: Option<all_the_time::Report>,
    ) -> Self {
        Self {
            #[cfg(feature = "alloc_tracker")]
            alloc_report,
            #[cfg(feature = "all_the_time")]
            time_report,
        }
    }

    /// Returns the allocation tracking report, if allocation tracking was configured.
    ///
    /// This method is only available when the `alloc_tracker` feature is enabled.
    /// Returns `None` if allocation tracking was not configured for this benchmark run.
    #[cfg(feature = "alloc_tracker")]
    #[must_use]
    pub fn allocs(&self) -> Option<&alloc_tracker::Report> {
        self.alloc_report.as_ref()
    }

    /// Returns the processor time tracking report, if processor time tracking was configured.
    ///
    /// This method is only available when the `all_the_time` feature is enabled.
    /// Returns `None` if processor time tracking was not configured for this benchmark run.
    #[cfg(feature = "all_the_time")]
    #[must_use]
    pub fn processor_time(&self) -> Option<&all_the_time::Report> {
        self.time_report.as_ref()
    }
}

/// Internal state for managing resource usage spans during benchmark execution.
#[derive(Debug)]
pub struct ResourceUsageState {
    #[cfg(feature = "alloc_tracker")]
    alloc_span: Option<alloc_tracker::ThreadSpan>,

    #[cfg(feature = "all_the_time")]
    time_span: Option<all_the_time::ThreadSpan>,
}

impl ResourceUsageState {
    /// Creates a new resource usage state from the builder configuration.
    #[must_use]
    pub(crate) fn new(
        builder: &ResourceUsageMeasureBuilder<'_>,
        operation_name: &str,
        iterations: u64,
    ) -> Self {
        Self {
            #[cfg(feature = "alloc_tracker")]
            alloc_span: builder.alloc_session.map(|session| {
                session
                    .operation(operation_name)
                    .measure_thread()
                    .iterations(iterations)
            }),

            #[cfg(feature = "all_the_time")]
            time_span: builder.time_session.map(|session| {
                session
                    .operation(operation_name)
                    .measure_thread()
                    .iterations(iterations)
            }),
        }
    }

    /// Converts the state into the final resource usage output.
    #[must_use]
    pub(crate) fn into_output(
        self,
        builder: &ResourceUsageMeasureBuilder<'_>,
    ) -> ResourceUsageOutput {
        // Drop the spans to record the measurements
        #[cfg(feature = "alloc_tracker")]
        let alloc_report = self.alloc_span.and_then(|span| {
            drop(span);
            builder.alloc_session.map(alloc_tracker::Session::to_report)
        });

        #[cfg(feature = "all_the_time")]
        let time_report = self.time_span.and_then(|span| {
            drop(span);
            builder.time_session.map(all_the_time::Session::to_report)
        });

        ResourceUsageOutput::new(
            #[cfg(feature = "alloc_tracker")]
            alloc_report,
            #[cfg(feature = "all_the_time")]
            time_report,
        )
    }
}

/// Creates a resource usage state factory function for the given builder and operation name.
///
/// This function handles the calculation of per-thread iterations to avoid double-counting
/// in parallel benchmark scenarios.
fn create_resource_usage_state_factory<'a, ThreadState>(
    builder: ResourceUsageMeasureBuilder<'a>,
    operation_name: &'a str,
) -> impl Fn(crate::args::MeasureWrapperBegin<'_, ThreadState>) -> ResourceUsageState + 'a {
    move |args| {
        // NB! As we are working with parallel benchmarking, we need to ensure we count
        // each GLOBAL iteration for comparable results. The measurement wrapper,
        // however is LOCAL to each thread. We would multi-count iterations if we just
        // used this as-is (with 4 threads, we would count 4x iterations).
        //
        // We fixup this with a simple division to offset it back again.
        // Ensure we never get 0 iterations by using max(1, division_result).
        #[expect(
            clippy::arithmetic_side_effects,
            reason = "NonZero eliminates division by zero"
        )]
        #[expect(
            clippy::integer_division,
            reason = "we accept imperfect accuracy - typical iteration counts are high enough for it not to matter"
        )]
        let iterations =
            (args.meta().iterations() / args.meta().thread_count().get() as u64).max(1);

        ResourceUsageState::new(&builder, operation_name, iterations)
    }
}

impl<'a> ResourceUsageExt<'a, ()> for crate::configure::RunInitial {
    type Output =
        crate::configure::RunWithWrapperState<'a, (), (), ResourceUsageState, ResourceUsageOutput>;

    fn measure_resource_usage<F>(self, operation_name: &'a str, configure: F) -> Self::Output
    where
        F: FnOnce(ResourceUsageMeasureBuilder<'a>) -> ResourceUsageMeasureBuilder<'a>,
    {
        let builder = configure(ResourceUsageMeasureBuilder::new());

        self.measure_wrapper(
            create_resource_usage_state_factory(builder.clone(), operation_name),
            move |state| state.into_output(&builder),
        )
    }
}

impl<'a, ThreadState> ResourceUsageExt<'a, ThreadState>
    for crate::configure::RunWithThreadState<'a, ThreadState>
{
    type Output = crate::configure::RunWithWrapperState<
        'a,
        ThreadState,
        (),
        ResourceUsageState,
        ResourceUsageOutput,
    >;

    fn measure_resource_usage<F>(self, operation_name: &'a str, configure: F) -> Self::Output
    where
        F: FnOnce(ResourceUsageMeasureBuilder<'a>) -> ResourceUsageMeasureBuilder<'a>,
    {
        let builder = configure(ResourceUsageMeasureBuilder::new());

        self.measure_wrapper(
            create_resource_usage_state_factory(builder.clone(), operation_name),
            move |state| state.into_output(&builder),
        )
    }
}

impl<'a, ThreadState, IterState> ResourceUsageExt<'a, ThreadState>
    for crate::configure::RunWithIterState<'a, ThreadState, IterState>
{
    type Output = crate::configure::RunWithWrapperState<
        'a,
        ThreadState,
        IterState,
        ResourceUsageState,
        ResourceUsageOutput,
    >;

    fn measure_resource_usage<F>(self, operation_name: &'a str, configure: F) -> Self::Output
    where
        F: FnOnce(ResourceUsageMeasureBuilder<'a>) -> ResourceUsageMeasureBuilder<'a>,
    {
        let builder = configure(ResourceUsageMeasureBuilder::new());

        self.measure_wrapper(
            create_resource_usage_state_factory(builder.clone(), operation_name),
            move |state| state.into_output(&builder),
        )
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::sync::LazyLock;

    use many_cpus::{ProcessorSet, SystemHardware};
    use new_zealand::nz;

    use super::ResourceUsageExt;
    use crate::{Run, ThreadPool};

    static TWO_PROCESSORS: LazyLock<Option<ProcessorSet>> = LazyLock::new(|| {
        SystemHardware::current()
            .processors()
            .to_builder()
            .take(nz!(2))
    });

    static FOUR_PROCESSORS: LazyLock<Option<ProcessorSet>> = LazyLock::new(|| {
        SystemHardware::current()
            .processors()
            .to_builder()
            .take(nz!(4))
    });

    #[test]
    fn module_loads() {
        // Basic test to ensure the module compiles and loads correctly under Miri.
        // This test does not require any OS functionality.
        let builder = super::ResourceUsageMeasureBuilder::new();
        // Just verify the builder can be created
        std::hint::black_box(builder);
    }

    #[test]
    #[cfg(all(not(miri), feature = "alloc_tracker"))] // Uses ThreadPool which requires OS threading functions that Miri cannot emulate.
    fn measure_resource_usage_allocs_only() {
        let allocs = alloc_tracker::Session::new();
        let mut pool = ThreadPool::new(
            SystemHardware::current()
                .processors()
                .to_builder()
                .take(nz!(1))
                .unwrap(),
        );

        let results = Run::new()
            .measure_resource_usage("test_operation", |measure| measure.allocs(&allocs))
            .iter(|_| {
                // Allocate some memory to generate allocation activity
                let _data = [1, 2, 3, 4, 5].to_vec();
            })
            .execute_on(&mut pool, 10);

        // Verify that we got results back
        assert!(results.measure_outputs().count() > 0);

        // Verify that allocation tracking worked
        for output in results.measure_outputs() {
            assert!(output.allocs().is_some());
        }

        // Verify that the session recorded the operation
        let report = allocs.to_report();
        assert!(!report.is_empty());
    }

    #[test]
    #[cfg(all(not(miri), feature = "all_the_time"))] // Uses ThreadPool which requires OS threading functions that Miri cannot emulate.
    fn measure_resource_usage_processor_time_only() {
        let processor_time = all_the_time::Session::new();
        let mut pool = ThreadPool::new(
            SystemHardware::current()
                .processors()
                .to_builder()
                .take(nz!(1))
                .unwrap(),
        );

        let results = Run::new()
            .measure_resource_usage("test_operation", |measure| {
                measure.processor_time(&processor_time)
            })
            .iter(|_| {
                // Perform some CPU-intensive work
                let mut sum = 0_u64;
                for i in 0_u64..1000 {
                    sum = sum.wrapping_add(i.wrapping_mul(i));
                }
                std::hint::black_box(sum);
            })
            .execute_on(&mut pool, 10);

        // Verify that we got results back
        assert!(results.measure_outputs().count() > 0);

        // Verify that processor time tracking worked
        for output in results.measure_outputs() {
            assert!(output.processor_time().is_some());
        }

        // Verify that the session recorded the operation
        let report = processor_time.to_report();
        assert!(!report.is_empty());
    }

    #[test]
    #[cfg(all(not(miri), feature = "alloc_tracker", feature = "all_the_time"))] // Uses ThreadPool which requires OS threading functions that Miri cannot emulate.
    fn measure_resource_usage_combined() {
        let allocs = alloc_tracker::Session::new();
        let processor_time = all_the_time::Session::new();
        let mut pool = ThreadPool::new(
            SystemHardware::current()
                .processors()
                .to_builder()
                .take(nz!(1))
                .unwrap(),
        );

        let results = Run::new()
            .measure_resource_usage("test_operation", |measure| {
                measure.allocs(&allocs).processor_time(&processor_time)
            })
            .iter(|_| {
                // Allocate memory and perform CPU work
                let _data = [1, 2, 3, 4, 5].to_vec();
                let mut sum = 0_u64;
                for i in 0_u64..100 {
                    sum = sum.wrapping_add(i);
                }
                std::hint::black_box(sum);
            })
            .execute_on(&mut pool, 5);

        // Verify that we got results back
        assert!(results.measure_outputs().count() > 0);

        // Verify that both types of tracking worked
        for output in results.measure_outputs() {
            assert!(output.allocs().is_some());
            assert!(output.processor_time().is_some());
        }

        // Verify that both sessions recorded the operations
        let alloc_report = allocs.to_report();
        assert!(!alloc_report.is_empty());

        let time_report = processor_time.to_report();
        assert!(!time_report.is_empty());
    }

    #[test]
    #[cfg(all(not(miri), feature = "alloc_tracker", feature = "all_the_time"))] // Uses ThreadPool which requires OS threading functions that Miri cannot emulate.
    fn api_supports_groups_in_any_order() {
        let Some(processors) = TWO_PROCESSORS.as_ref() else {
            println!("Skipping test: not enough processors");
            return;
        };

        let mut pool = ThreadPool::new(processors.clone());

        let allocs = alloc_tracker::Session::new();
        let processor_time = all_the_time::Session::new();

        // Test 1: .measure_resource_usage() before .groups()
        let results1 = Run::new()
            .prepare_iter(|_| 42_i32)
            .measure_resource_usage("test1", |measure| {
                measure.allocs(&allocs).processor_time(&processor_time)
            })
            .groups(new_zealand::nz!(2))
            .iter(|_| {
                let _data = [1, 2, 3, 4, 5].to_vec();
            })
            .execute_on(&mut pool, 10);

        assert!(results1.measure_outputs().count() > 0);

        // Test 2: .groups() before .measure_resource_usage()
        let results2 = Run::new()
            .prepare_iter(|_| 42_i32)
            .groups(new_zealand::nz!(2))
            .measure_resource_usage("test2", |measure| {
                measure.allocs(&allocs).processor_time(&processor_time)
            })
            .iter(|_| {
                let _data = [1, 2, 3, 4, 5].to_vec();
            })
            .execute_on(&mut pool, 10);

        assert!(results2.measure_outputs().count() > 0);
    }

    #[test]
    fn api_supports_groups_immediately_after_new() {
        // Test that Run::new().groups() works
        let _run = Run::new().groups(new_zealand::nz!(2));

        // Test the full chain with groups first
        let _run = Run::new().groups(new_zealand::nz!(2)).iter(|_| {
            std::hint::black_box(42);
        });
    }

    #[test]
    #[cfg(all(not(miri), feature = "alloc_tracker"))] // Uses ThreadPool which requires OS threading functions that Miri cannot emulate.
    fn api_supports_measure_resource_usage_after_groups_only() {
        let Some(processors) = TWO_PROCESSORS.as_ref() else {
            println!("Skipping test: not enough processors");
            return;
        };

        let mut pool = ThreadPool::new(processors.clone());

        let allocs = alloc_tracker::Session::new();

        // Test pattern: Run::new().groups().measure_resource_usage()
        let results = Run::new()
            .groups(new_zealand::nz!(2))
            .measure_resource_usage("test", |measure| measure.allocs(&allocs))
            .iter(|_| {
                let _data = [1, 2, 3, 4, 5].to_vec();
            })
            .execute_on(&mut pool, 10);

        assert!(results.measure_outputs().count() > 0);
    }

    #[test]
    #[cfg(all(not(miri), feature = "alloc_tracker"))] // Uses ThreadPool which requires OS threading functions that Miri cannot emulate.
    fn api_supports_original_pattern_groups_prepare_iter_measure() {
        let Some(processors) = TWO_PROCESSORS.as_ref() else {
            println!("Skipping test: not enough processors");
            return;
        };

        let mut pool = ThreadPool::new(processors.clone());

        let allocs = alloc_tracker::Session::new();

        // Test original pattern: Run::new().groups().prepare_iter().measure_resource_usage()
        let results = Run::new()
            .groups(new_zealand::nz!(2))
            .prepare_iter(|_| 42_i32)
            .measure_resource_usage("test", |measure| measure.allocs(&allocs))
            .iter(|_| {
                let _data = [1, 2, 3, 4, 5].to_vec();
            })
            .execute_on(&mut pool, 10);

        assert!(results.measure_outputs().count() > 0);
    }

    #[test]
    #[cfg(all(not(miri), feature = "alloc_tracker"))] // Uses ThreadPool which requires OS threading functions that Miri cannot emulate.
    fn measure_resource_usage_with_thread_state() {
        let allocs = alloc_tracker::Session::new();
        let mut pool = ThreadPool::new(
            SystemHardware::current()
                .processors()
                .to_builder()
                .take(nz!(1))
                .unwrap(),
        );

        let results = Run::new()
            .prepare_thread(|_| String::from("thread_data"))
            .measure_resource_usage("test_with_state", |measure| measure.allocs(&allocs))
            .iter(|args| {
                // Use thread state and allocate memory
                let _combined = format!("{}_allocated", args.thread_state());
            })
            .execute_on(&mut pool, 5);

        // Verify that we got results back
        assert!(results.measure_outputs().count() > 0);

        // Verify that allocation tracking worked
        for output in results.measure_outputs() {
            assert!(output.allocs().is_some());
        }

        // Verify that the session recorded the operation
        let report = allocs.to_report();
        assert!(!report.is_empty());
    }

    #[test]
    #[cfg(all(not(miri), feature = "alloc_tracker"))] // Uses ThreadPool which requires OS threading functions that Miri cannot emulate.
    fn create_resource_usage_state_factory_divides_iterations_correctly() {
        // Skip test if there is only one processor to avoid division by 1 (no effect)
        let Some(processors) = FOUR_PROCESSORS.as_ref() else {
            println!(
                "Skipping test create_resource_usage_state_factory_divides_iterations_correctly: not enough processors"
            );
            return;
        };

        let allocs = alloc_tracker::Session::new();
        let mut pool = ThreadPool::new(processors);

        // Each thread will execute 1000 iterations, but the allocation tracker should
        // record the iterations as 1000/4 = 250 per thread to get correct averages
        let iterations = 1000_u64;
        #[expect(
            clippy::integer_division,
            reason = "testing the exact division behavior we want to verify"
        )]
        let expected_iterations_per_thread = iterations / pool.thread_count().get() as u64;

        let results = Run::new()
            .measure_resource_usage("iteration_division_test", |measure| measure.allocs(&allocs))
            .iter(|_| {
                // For this test, we do not need to actually allocate since we are just
                // testing the iteration division logic, not the allocation tracking itself
                std::hint::black_box(42);
            })
            .execute_on(&mut pool, iterations);

        // Verify that we got results back
        assert!(results.measure_outputs().count() > 0);

        // Verify that allocation tracking worked (even if no allocations happened)
        for output in results.measure_outputs() {
            assert!(output.allocs().is_some());
        }

        // The key test: Verify that the allocation tracker got the divided iteration count
        // rather than the full iteration count. This ensures proper average calculations.
        let report = allocs.to_report();
        assert!(!report.is_empty());

        let operations: Vec<_> = report.operations().collect();
        let (_operation_name, operation_stats) = operations
            .iter()
            .find(|(name, _)| *name == "iteration_division_test")
            .unwrap();

        // Each thread should report the divided iteration count, not the full count
        // With 4 threads, total tracked iterations should be 4 * (1000/4) = 1000, not 4000
        let total_tracked_iterations = operation_stats.total_iterations();
        let expected_total_tracked_iterations =
            pool.thread_count().get() as u64 * expected_iterations_per_thread;

        assert_eq!(
            total_tracked_iterations, expected_total_tracked_iterations,
            "The create_resource_usage_state_factory should divide iterations per thread \
             to avoid inflating the iteration count. Expected {expected_total_tracked_iterations} iterations tracked, got {total_tracked_iterations}"
        );

        // Since we didn't allocate, we expect 0 mean, which verifies our test setup is working
        let mean_bytes = operation_stats.mean();
        assert_eq!(
            mean_bytes, 0,
            "Expected 0 mean bytes since no allocations occurred, got {mean_bytes}"
        );
    }
}