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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
use std::sync::{Arc, Mutex};
use crate::{FrameData, FrameSinkId};
#[derive(Clone)]
pub struct FrameView {
recent: std::collections::VecDeque<Arc<FrameData>>,
max_recent: usize,
slowest: std::collections::BinaryHeap<OrderedByDuration>,
max_slow: usize,
}
impl Default for FrameView {
fn default() -> Self {
let max_recent = 60 * 60 * 5;
let max_slow = 256;
Self {
recent: std::collections::VecDeque::with_capacity(max_recent),
max_recent,
slowest: std::collections::BinaryHeap::with_capacity(max_slow),
max_slow,
}
}
}
impl FrameView {
pub fn is_empty(&self) -> bool {
self.recent.is_empty() && self.slowest.is_empty()
}
pub fn add_frame(&mut self, new_frame: Arc<FrameData>) {
if let Some(last) = self.recent.back() {
if new_frame.frame_index() <= last.frame_index() {
self.recent.clear();
self.slowest.clear();
}
}
let add_to_slowest = if self.slowest.len() < self.max_slow {
true
} else if let Some(fastest_of_the_slow) = self.slowest.peek() {
new_frame.duration_ns() > fastest_of_the_slow.0.duration_ns()
} else {
false
};
if add_to_slowest {
self.slowest.push(OrderedByDuration(new_frame.clone()));
while self.slowest.len() > self.max_slow {
self.slowest.pop();
}
}
if let Some(last) = self.recent.back() {
last.pack();
}
self.recent.push_back(new_frame);
while self.recent.len() > self.max_recent {
self.recent.pop_front();
}
}
pub fn latest_frame(&self) -> Option<Arc<FrameData>> {
self.recent.back().cloned()
}
pub fn recent_frames(&self) -> impl Iterator<Item = &Arc<FrameData>> {
self.recent.iter()
}
pub fn slowest_frames_chronological(&self) -> Vec<Arc<FrameData>> {
let mut frames: Vec<_> = self.slowest.iter().map(|f| f.0.clone()).collect();
frames.sort_by_key(|frame| frame.frame_index());
frames
}
pub fn all_uniq(&self) -> Vec<Arc<FrameData>> {
let mut all: Vec<_> = self.slowest.iter().map(|f| f.0.clone()).collect();
all.extend(self.recent.iter().cloned());
all.sort_by_key(|frame| frame.frame_index());
all.dedup_by_key(|frame| frame.frame_index());
all
}
pub fn clear_slowest(&mut self) {
self.slowest.clear();
}
pub fn max_recent(&self) -> usize {
self.max_recent
}
pub fn set_max_recent(&mut self, max_recent: usize) {
self.max_recent = max_recent;
}
pub fn max_slow(&self) -> usize {
self.max_slow
}
pub fn set_max_slow(&mut self, max_slow: usize) {
self.max_slow = max_slow;
}
#[cfg(feature = "serialization")]
#[cfg(not(target_arch = "wasm32"))]
pub fn save_to_path(&self, path: &std::path::Path) -> anyhow::Result<()> {
let mut file = std::fs::File::create(path)?;
self.save_to_writer(&mut file)
}
#[cfg(feature = "serialization")]
#[cfg(not(target_arch = "wasm32"))]
pub fn save_to_writer(&self, write: &mut impl std::io::Write) -> anyhow::Result<()> {
write.write_all(b"PUF0")?;
let slowest_frames = self.slowest.iter().map(|f| &f.0);
let mut frames: Vec<_> = slowest_frames.chain(self.recent.iter()).collect();
frames.sort_by_key(|frame| frame.frame_index());
frames.dedup_by_key(|frame| frame.frame_index());
for frame in frames {
frame.write_into(write)?;
}
Ok(())
}
#[cfg(feature = "serialization")]
pub fn load_path(path: &std::path::Path) -> anyhow::Result<Self> {
let mut file = std::fs::File::open(path)?;
Self::load_reader(&mut file)
}
#[cfg(feature = "serialization")]
pub fn load_reader(read: &mut impl std::io::Read) -> anyhow::Result<Self> {
let mut magic = [0_u8; 4];
read.read_exact(&mut magic)?;
if &magic != b"PUF0" {
anyhow::bail!("Expected .puffin magic header of 'PUF0', found {:?}", magic);
}
let mut slf = Self {
max_recent: usize::MAX,
..Default::default()
};
while let Some(frame) = FrameData::read_next(read)? {
slf.add_frame(frame.into());
}
Ok(slf)
}
}
pub fn select_slowest(frames: &[Arc<FrameData>], max: usize) -> Vec<Arc<FrameData>> {
let mut slowest: std::collections::BinaryHeap<OrderedByDuration> = Default::default();
for frame in frames {
slowest.push(OrderedByDuration(frame.clone()));
while slowest.len() > max {
slowest.pop();
}
}
let mut slowest: Vec<_> = slowest.drain().map(|x| x.0).collect();
slowest.sort_by_key(|frame| frame.frame_index());
slowest
}
#[derive(Clone)]
struct OrderedByDuration(Arc<FrameData>);
impl PartialEq for OrderedByDuration {
fn eq(&self, other: &Self) -> bool {
self.0.duration_ns().eq(&other.0.duration_ns())
}
}
impl Eq for OrderedByDuration {}
impl PartialOrd for OrderedByDuration {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for OrderedByDuration {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.duration_ns().cmp(&other.0.duration_ns()).reverse()
}
}
pub struct GlobalFrameView {
sink_id: FrameSinkId,
view: Arc<Mutex<FrameView>>,
}
impl Default for GlobalFrameView {
fn default() -> Self {
let view = Arc::new(Mutex::new(FrameView::default()));
let view_clone = view.clone();
let sink_id = crate::GlobalProfiler::lock().add_sink(Box::new(move |frame| {
view_clone.lock().unwrap().add_frame(frame);
}));
Self { sink_id, view }
}
}
impl Drop for GlobalFrameView {
fn drop(&mut self) {
crate::GlobalProfiler::lock().remove_sink(self.sink_id);
}
}
impl GlobalFrameView {
pub fn lock(&self) -> std::sync::MutexGuard<'_, FrameView> {
self.view.lock().unwrap()
}
}