cpu_cycles_reader/
instant.rs

1use std::ops::Sub;
2
3use libc::c_int;
4
5use crate::{Cycles, Error, Result};
6
7#[derive(Debug, Clone, Copy)]
8pub struct CyclesInstant {
9    cpu: c_int,
10    raw: Cycles,
11}
12
13impl CyclesInstant {
14    pub(crate) const fn new(cpu: c_int, raw: Cycles) -> Self {
15        Self { cpu, raw }
16    }
17
18    /// Calculate the number of cpu cycles between two recordings
19    ///
20    /// # Panics
21    ///
22    /// If the two records are not the same cpu, an error will be returned.
23    #[must_use]
24    pub fn cycles_since(&self, other: Self) -> Cycles {
25        self.cycles_since_checked(other).unwrap()
26    }
27
28    /// Calculate the number of cpu cycles between two recordings
29    ///
30    /// # Errors
31    ///
32    /// If the two records are not the same cpu, an error will be returned
33    pub fn cycles_since_checked(&self, other: Self) -> Result<Cycles> {
34        if self.cpu == other.cpu {
35            Ok(self.raw - other.raw)
36        } else {
37            Err(Error::InconsistentCore)
38        }
39    }
40}
41
42impl Sub for CyclesInstant {
43    type Output = Cycles;
44
45    fn sub(self, other: Self) -> Self::Output {
46        self.cycles_since(other)
47    }
48}