aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_prof/src/memory_usage.rs
blob: 2bde8fb5fbafc5ddc2f9de8b4da404fba3017599 (plain)
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
use std::fmt;

pub struct MemoryUsage {
    pub allocated: Bytes,
    pub resident: Bytes,
}

impl MemoryUsage {
    #[cfg(feature = "jemalloc")]
    pub fn current() -> MemoryUsage {
        jemalloc_ctl::epoch().unwrap();
        MemoryUsage {
            allocated: Bytes(jemalloc_ctl::stats::allocated().unwrap()),
            resident: Bytes(jemalloc_ctl::stats::resident().unwrap()),
        }
    }

    #[cfg(not(feature = "jemalloc"))]
    pub fn current() -> MemoryUsage {
        MemoryUsage { allocated: Bytes(0), resident: Bytes(0) }
    }
}

impl fmt::Display for MemoryUsage {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{} allocated {} resident", self.allocated, self.resident,)
    }
}

#[derive(Default)]
pub struct Bytes(usize);

impl fmt::Display for Bytes {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let bytes = self.0;
        if bytes < 4096 {
            return write!(f, "{} bytes", bytes);
        }
        let kb = bytes / 1024;
        if kb < 4096 {
            return write!(f, "{}kb", kb);
        }
        let mb = kb / 1024;
        write!(f, "{}mb", mb)
    }
}

impl std::ops::AddAssign<usize> for Bytes {
    fn add_assign(&mut self, x: usize) {
        self.0 += x;
    }
}