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
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use std::{
    sync::atomic::{self, AtomicBool, AtomicUsize},
    time::Duration,
};

use human_repr::HumanCount;
use memory_stats::memory_stats;
use tracing::info;

pub struct MemStatsTracker {
    check_interval: Duration,
    peak_physical_mem: AtomicUsize,
    cancelled: AtomicBool,
}

impl MemStatsTracker {
    pub fn new(check_interval: Duration) -> Self {
        assert!(check_interval > Duration::default());

        Self {
            check_interval,
            peak_physical_mem: Default::default(),
            cancelled: Default::default(),
        }
    }

    /// A blocking loop that records peak resident set size periodically
    pub async fn run_loop(&self) {
        while !self.cancelled.load(atomic::Ordering::Relaxed) {
            if let Some(usage) = memory_stats() {
                self.peak_physical_mem
                    .fetch_max(usage.physical_mem, atomic::Ordering::Relaxed);
            }
            tokio::time::sleep(self.check_interval).await;
        }
    }
}

impl Default for MemStatsTracker {
    fn default() -> Self {
        Self::new(Duration::from_millis(1000))
    }
}

impl Drop for MemStatsTracker {
    fn drop(&mut self) {
        self.cancelled.store(true, atomic::Ordering::Relaxed);
        info!(
            "Peak physical memory usage: {}",
            self.peak_physical_mem
                .load(atomic::Ordering::Relaxed)
                .human_count_bytes()
        );
    }
}