aboutsummaryrefslogtreecommitdiffstats
path: root/components/profile_traits/energy.rs
blob: 93891df4adb968b34628b0a6899b57d5f1500436 (plain) (blame)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

#[cfg(feature = "energy-profiling")]
pub fn read_energy_uj() -> u64 {
    energymon::read_energy_uj()
}

#[cfg(not(feature = "energy-profiling"))]
pub fn read_energy_uj() -> u64 {
    0
}

#[cfg(feature = "energy-profiling")]
pub fn energy_interval_ms() -> u32 {
    energymon::get_min_interval_ms()
}

#[cfg(not(feature = "energy-profiling"))]
pub fn energy_interval_ms() -> u32 {
    1000
}

#[cfg(feature = "energy-profiling")]
mod energymon {
    extern crate energy_monitor;
    extern crate energymon;

    use self::energy_monitor::EnergyMonitor;
    use self::energymon::EnergyMon;
    use std::mem;
    use std::sync::{Once, ONCE_INIT};

    static mut EM: Option<*mut EnergyMon> = None;

    fn init() {
        // can't use lazy_static macro for EM (no Sync trait for EnergyMon)
        static ONCE: Once = ONCE_INIT;
        ONCE.call_once(|| {
            if let Ok(em) = EnergyMon::new() {
                println!("Started energy monitoring from: {}", em.source());
                unsafe {
                    EM = Some(mem::transmute(Box::new(em)));
                }
            }
        });
    }

    /// Read energy from the energy monitor, otherwise return 0.
    pub fn read_energy_uj() -> u64 {
        init();
        unsafe {
            // EnergyMon implementations of EnergyMonitor always return a value
            EM.map_or(0, |em| (*em).read_uj().unwrap())
        }
    }

    pub fn get_min_interval_ms() -> u32 {
        init();
        unsafe { EM.map_or(0, |em| ((*em).interval_us() as f64 / 1000.0).ceil() as u32) }
    }

}