fxprof_processed_profile/
cpu_delta.rs

1use std::time::Duration;
2
3use serde::ser::{Serialize, Serializer};
4
5/// The amount of CPU time between thread samples.
6///
7/// This is used in the Firefox Profiler UI to draw an activity graph per thread.
8///
9/// A thread only runs on one CPU at any time, and can get scheduled off and on
10/// the CPU between two samples. The CPU delta is the accumulation of time it
11/// was running on the CPU.
12#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
13pub struct CpuDelta {
14    micros: u64,
15}
16
17impl From<Duration> for CpuDelta {
18    fn from(duration: Duration) -> Self {
19        Self {
20            micros: duration.as_micros() as u64,
21        }
22    }
23}
24
25impl CpuDelta {
26    /// A CPU delta of zero.
27    pub const ZERO: Self = Self { micros: 0 };
28
29    /// Create a CPU delta from integer nanoseconds.
30    pub fn from_nanos(nanos: u64) -> Self {
31        Self {
32            micros: nanos / 1000,
33        }
34    }
35
36    /// Create a CPU delta from integer microseconds.
37    pub fn from_micros(micros: u64) -> Self {
38        Self { micros }
39    }
40
41    /// Create a CPU delta from float milliseconds.
42    pub fn from_millis(millis: f64) -> Self {
43        Self {
44            micros: (millis * 1_000.0) as u64,
45        }
46    }
47
48    /// Whether the CPU delta is zero.
49    pub fn is_zero(&self) -> bool {
50        self.micros == 0
51    }
52}
53
54impl Serialize for CpuDelta {
55    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
56        // CPU deltas are serialized as float microseconds, because
57        // we set profile.meta.sampleUnits.threadCPUDelta to "µs".
58        self.micros.serialize(serializer)
59    }
60}