1use std::collections::VecDeque;
21use std::fmt::{self, Write as _};
22use std::ops::Range;
23use std::time::{Duration, Instant};
24
25use nadir_codec::json::{self, Value};
26use nadir_core::profile::ScopeRecord;
27
28use crate::{Plot, Ui};
29
30pub const PROFILER_FRAMES: usize = 300;
32
33pub const PROFILER_RECORDS: usize = 32_768;
37
38const RATE_FRAMES: usize = 60;
40
41const GRAPH_TOP_MS: f32 = 1000.0 / 30.0;
44
45const GRAPH_HEIGHT: f32 = 60.0;
47
48const PID: i64 = 1;
50const TID: i64 = 1;
51
52const GPU_TID: i64 = 2;
54
55#[non_exhaustive]
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub struct FrameTiming {
59 pub start: Instant,
61 pub length: Duration,
63 pub work: Duration,
66}
67
68impl FrameTiming {
69 pub fn new(start: Instant, length: Duration, work: Duration) -> Self {
72 Self {
73 start,
74 length,
75 work,
76 }
77 }
78}
79
80#[non_exhaustive]
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85pub struct GpuTiming {
86 pub submitted: Instant,
91 pub world: Duration,
93 pub output: Duration,
95}
96
97impl GpuTiming {
98 pub fn new(submitted: Instant, world: Duration, output: Duration) -> Self {
101 Self {
102 submitted,
103 world,
104 output,
105 }
106 }
107
108 pub fn total(&self) -> Duration {
110 self.world + self.output
111 }
112}
113
114#[non_exhaustive]
116#[derive(Clone, Copy, Debug)]
117pub struct ProfiledFrame<'a> {
118 pub index: u64,
120 pub timing: FrameTiming,
122 pub gpu: Option<GpuTiming>,
125 pub records: &'a [ScopeRecord],
128 pub dropped: usize,
130}
131
132#[non_exhaustive]
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
135pub struct ProfilerResponse {
136 pub write_trace: bool,
140}
141
142#[derive(Clone, Copy, Debug)]
144struct Slot {
145 index: u64,
146 timing: FrameTiming,
147 gpu: Option<GpuTiming>,
148 first: usize,
149 len: usize,
150 dropped: usize,
151}
152
153impl Slot {
154 fn range(&self) -> Range<usize> {
155 self.first..self.first + self.len
156 }
157}
158
159pub struct Profiler {
172 slots: VecDeque<Slot>,
173 records: Vec<ScopeRecord>,
176 head: usize,
178 next: u64,
180 lengths: [Duration; RATE_FRAMES],
182 rate_next: usize,
183 rate_count: usize,
184 paused: bool,
185 selected: Option<u64>,
186 order: Vec<ScopeRecord>,
189 keys: Vec<OrderKey>,
190 note: String,
191}
192
193impl Default for Profiler {
194 fn default() -> Self {
195 Self::new()
196 }
197}
198
199impl Profiler {
200 pub fn new() -> Self {
202 Self {
203 slots: VecDeque::with_capacity(PROFILER_FRAMES),
204 records: Vec::new(),
205 head: 0,
206 next: 0,
207 lengths: [Duration::ZERO; RATE_FRAMES],
208 rate_next: 0,
209 rate_count: 0,
210 paused: false,
211 selected: None,
212 order: Vec::new(),
213 keys: Vec::new(),
214 note: String::new(),
215 }
216 }
217
218 pub fn push(&mut self, timing: FrameTiming, records: &[ScopeRecord]) {
221 self.lengths[self.rate_next] = timing.length;
222 self.rate_next = (self.rate_next + 1) % RATE_FRAMES;
223 self.rate_count = (self.rate_count + 1).min(RATE_FRAMES);
224 let index = self.next;
225 self.next += 1;
226 if self.paused {
227 return;
228 }
229 if self.records.is_empty() {
230 let blank = ScopeRecord {
231 name: "",
232 start: timing.start,
233 duration: Duration::ZERO,
234 depth: 0,
235 };
236 self.records = vec![blank; PROFILER_RECORDS];
237 }
238 let len = records.len().min(PROFILER_RECORDS);
239 let first = if self.head + len > PROFILER_RECORDS {
240 0
241 } else {
242 self.head
243 };
244 let range = first..first + len;
245 while self.slots.len() == PROFILER_FRAMES
246 || self
247 .slots
248 .iter()
249 .any(|slot| overlaps(&slot.range(), &range))
250 {
251 self.slots.pop_front();
252 }
253 self.records[range].copy_from_slice(&records[..len]);
254 self.head = first + len;
255 self.slots.push_back(Slot {
256 index,
257 timing,
258 gpu: None,
259 first,
260 len,
261 dropped: records.len() - len,
262 });
263 }
264
265 pub fn next_index(&self) -> u64 {
268 self.next
269 }
270
271 pub fn set_gpu(&mut self, index: u64, timing: GpuTiming) -> bool {
276 match self.slots.iter_mut().rev().find(|slot| slot.index == index) {
278 Some(slot) => {
279 slot.gpu = Some(timing);
280 true
281 }
282 None => false,
283 }
284 }
285
286 pub fn len(&self) -> usize {
288 self.slots.len()
289 }
290
291 pub fn is_empty(&self) -> bool {
293 self.slots.is_empty()
294 }
295
296 pub fn frames(&self) -> impl ExactSizeIterator<Item = ProfiledFrame<'_>> + '_ {
298 self.slots.iter().map(|slot| self.view(slot))
299 }
300
301 pub fn frame(&self, index: u64) -> Option<ProfiledFrame<'_>> {
303 self.slot(index).map(|slot| self.view(slot))
304 }
305
306 pub fn frame_rate(&self) -> f32 {
309 let total: Duration = self.lengths[..self.rate_count].iter().sum();
310 if total.is_zero() {
311 0.0
312 } else {
313 self.rate_count as f32 / total.as_secs_f32()
314 }
315 }
316
317 pub fn paused(&self) -> bool {
319 self.paused
320 }
321
322 pub fn set_paused(&mut self, paused: bool) {
324 self.paused = paused;
325 }
326
327 pub fn selected(&self) -> Option<u64> {
329 self.selected
330 }
331
332 pub fn select(&mut self, index: Option<u64>) {
334 self.selected = index;
335 }
336
337 pub fn set_note(&mut self, note: impl fmt::Display) {
340 self.note.clear();
341 let _ = write!(self.note, "{note}");
343 }
344
345 pub fn show(&mut self, ui: &mut Ui<'_>) -> ProfilerResponse {
352 let mut response = ProfilerResponse::default();
353 ui.horizontal(|ui| {
354 ui.checkbox("Paused", &mut self.paused);
355 response.write_trace = ui.button("Write trace").clicked;
356 });
357 if !self.note.is_empty() {
358 ui.label(&self.note);
359 }
360 let selected = self
361 .selected
362 .and_then(|index| self.slots.iter().position(|slot| slot.index == index));
363 let plot = Plot {
364 range: 0.0..=GRAPH_TOP_MS,
365 height: GRAPH_HEIGHT,
366 selected,
367 };
368 let values = self.slots.iter().map(|slot| millis(slot.timing.work));
369 let cpu = ui.plot("CPU ms##graph", values, plot.clone());
370 let values = self
372 .slots
373 .iter()
374 .map(|slot| slot.gpu.map_or(f32::NAN, |gpu| millis(gpu.total())));
375 let gpu = ui.plot("GPU ms##gpu", values, plot);
376 let clicked = cpu.clicked.or(gpu.clicked);
377 if let Some(slot) = clicked.and_then(|at| self.slots.get(at)) {
378 self.selected = Some(slot.index);
379 }
380 let hovered = cpu.hovered.or(gpu.hovered);
381 match hovered.and_then(|at| self.slots.get(at)) {
382 Some(slot) => match slot.gpu {
383 Some(gpu) => ui.label(format_args!(
384 "frame {}: {:.2} ms CPU, {:.2} ms GPU, {:.2} ms long",
385 slot.index,
386 millis(slot.timing.work),
387 millis(gpu.total()),
388 millis(slot.timing.length)
389 )),
390 None => ui.label(format_args!(
391 "frame {}: {:.2} ms CPU, {:.2} ms long",
392 slot.index,
393 millis(slot.timing.work),
394 millis(slot.timing.length)
395 )),
396 },
397 None => ui.label(format_args!(
398 "{} frames, {:.0} a second",
399 self.slots.len(),
400 self.frame_rate()
401 )),
402 }
403 ui.separator();
404 let Some(index) = self.selected else {
405 ui.label("Click a frame for its scopes.");
406 return response;
407 };
408 let Some(&slot) = self.slot(index) else {
409 ui.label(format_args!("Frame {index} is gone: click another."));
410 return response;
411 };
412 ui.label(format_args!(
413 "frame {}: {} scopes, {:.3} ms CPU",
414 slot.index,
415 slot.len,
416 millis(slot.timing.work)
417 ));
418 if slot.dropped > 0 {
419 ui.label(format_args!("{} more scopes not kept", slot.dropped));
420 }
421 match slot.gpu {
422 Some(gpu) => ui.label(format_args!(
423 "GPU {:.3} ms: world {:.3}, output {:.3}",
424 millis(gpu.total()),
425 millis(gpu.world),
426 millis(gpu.output)
427 )),
428 None => ui.label("no GPU time"),
429 }
430 start_order(&self.records[slot.range()], &mut self.keys, &mut self.order);
431 tree(ui, &self.order);
432 response
433 }
434
435 pub fn trace_json(&self) -> String {
466 let origin = self.slots.front().map(|slot| slot.timing.start);
467 let since =
468 |at: Instant| origin.map_or(0, |origin| micros(at.saturating_duration_since(origin)));
469 let span = |start: Instant, duration: Duration| {
470 let ts = since(start);
471 (ts, since(start + duration) - ts)
472 };
473 let timed = self.slots.iter().filter(|slot| slot.gpu.is_some()).count();
474 let mut events = Vec::with_capacity(2 + self.slots.len() + self.records_held() + 3 * timed);
475 let (mut keys, mut ordered) = (Vec::new(), Vec::new());
476 events.push(thread_name(TID, "main"));
477 if timed > 0 {
478 events.push(thread_name(GPU_TID, "gpu"));
479 }
480 let mut gpu_free: Option<Instant> = None;
482 for frame in self.frames() {
483 let index = i64::try_from(frame.index).unwrap_or(i64::MAX);
484 let cpu_ms = micros(frame.timing.work) as f64 / 1000.0;
485 let args = object(vec![
486 ("index", Value::Int(index)),
487 ("cpu_ms", Value::Float(cpu_ms)),
488 ]);
489 let (ts, dur) = span(frame.timing.start, frame.timing.length);
490 events.push(complete(TID, "frame", ts, dur, Some(args)));
491 start_order(frame.records, &mut keys, &mut ordered);
492 for record in &ordered {
493 let (ts, dur) = span(record.start, record.duration);
494 events.push(complete(TID, record.name, ts, dur, None));
495 }
496 let Some(gpu) = frame.gpu else {
497 continue;
498 };
499 let start = gpu_free.map_or(gpu.submitted, |free| free.max(gpu.submitted));
500 let between = start + gpu.world;
501 let end = between + gpu.output;
502 gpu_free = Some(end);
503 let gpu_ms = micros(gpu.total()) as f64 / 1000.0;
504 let args = object(vec![
505 ("index", Value::Int(index)),
506 ("gpu_ms", Value::Float(gpu_ms)),
507 ]);
508 let (start, between, end) = (since(start), since(between), since(end));
511 events.push(complete(GPU_TID, "frame", start, end - start, Some(args)));
512 events.push(complete(GPU_TID, "world", start, between - start, None));
513 events.push(complete(GPU_TID, "output", between, end - between, None));
514 }
515 json::to_string_compact(&object(vec![("traceEvents", Value::Array(events))]))
516 }
517
518 fn records_held(&self) -> usize {
519 self.slots.iter().map(|slot| slot.len).sum()
520 }
521
522 fn slot(&self, index: u64) -> Option<&Slot> {
523 self.slots.iter().find(|slot| slot.index == index)
524 }
525
526 fn view(&self, slot: &Slot) -> ProfiledFrame<'_> {
527 ProfiledFrame {
528 index: slot.index,
529 timing: slot.timing,
530 gpu: slot.gpu,
531 records: &self.records[slot.range()],
532 dropped: slot.dropped,
533 }
534 }
535}
536
537fn tree(ui: &mut Ui<'_>, records: &[ScopeRecord]) {
541 let mut at = 0;
542 let mut position = 0_usize;
543 while let Some(record) = records.get(at) {
544 let deeper = records[at + 1..]
545 .iter()
546 .take_while(|child| child.depth > record.depth)
547 .count();
548 let children = &records[at + 1..at + 1 + deeper];
549 let ms = f64::from(millis(record.duration));
550 if children.is_empty() {
551 ui.label(format_args!(" {} {ms:.3} ms", record.name));
552 } else {
553 ui.tree_node(
556 format_args!("{} {ms:.3} ms##{position}:{}", record.name, record.name),
557 |ui| tree(ui, children),
558 );
559 }
560 at += 1 + deeper;
561 position += 1;
562 }
563}
564
565type OrderKey = (u32, u32, u32);
568
569fn start_order(records: &[ScopeRecord], keys: &mut Vec<OrderKey>, out: &mut Vec<ScopeRecord>) {
582 keys.clear();
583 for (index, record) in records.iter().enumerate() {
584 let mut first = index;
585 while first > 0 && records[first - 1].depth > record.depth {
586 first = keys[first - 1].0 as usize;
588 }
589 keys.push((first as u32, record.depth, index as u32));
591 }
592 keys.sort_unstable();
593 out.clear();
594 out.extend(keys.iter().map(|&(_, _, index)| records[index as usize]));
595}
596
597fn overlaps(a: &Range<usize>, b: &Range<usize>) -> bool {
598 a.start < b.end && b.start < a.end
599}
600
601fn millis(duration: Duration) -> f32 {
602 duration.as_secs_f32() * 1000.0
603}
604
605fn micros(duration: Duration) -> i64 {
607 i64::try_from(duration.as_micros()).unwrap_or(i64::MAX)
608}
609
610fn object(members: Vec<(&str, Value)>) -> Value {
611 Value::Object(
612 members
613 .into_iter()
614 .map(|(key, value)| (key.to_string(), value))
615 .collect(),
616 )
617}
618
619fn thread_name(tid: i64, name: &str) -> Value {
621 object(vec![
622 ("name", Value::String("thread_name".to_string())),
623 ("ph", Value::String("M".to_string())),
624 ("pid", Value::Int(PID)),
625 ("tid", Value::Int(tid)),
626 (
627 "args",
628 object(vec![("name", Value::String(name.to_string()))]),
629 ),
630 ])
631}
632
633fn complete(tid: i64, name: &str, ts: i64, dur: i64, args: Option<Value>) -> Value {
635 let mut members = vec![
636 ("name", Value::String(name.to_string())),
637 ("ph", Value::String("X".to_string())),
638 ("ts", Value::Int(ts)),
639 ("dur", Value::Int(dur)),
640 ("pid", Value::Int(PID)),
641 ("tid", Value::Int(tid)),
642 ];
643 if let Some(args) = args {
644 members.push(("args", args));
645 }
646 object(members)
647}
648
649#[cfg(test)]
650mod tests {
651 use nadir_codec::Limits;
652
653 use super::*;
654
655 const MS: Duration = Duration::from_millis(1);
656 const US: Duration = Duration::from_micros(1);
657
658 fn record(name: &'static str, start: Instant, duration: Duration, depth: u32) -> ScopeRecord {
659 ScopeRecord {
660 name,
661 start,
662 duration,
663 depth,
664 }
665 }
666
667 fn frame_records(start: Instant) -> Vec<ScopeRecord> {
670 vec![
671 record("player_move", start + 10 * US, 100 * US, 1),
672 record("movement", start + 120 * US, 300 * US, 1),
673 record("nadir::tick", start + 5 * US, 500 * US, 0),
674 record("nadir::render", start + 600 * US, 2 * MS, 0),
675 ]
676 }
677
678 fn timing(start: Instant) -> FrameTiming {
679 FrameTiming::new(start, 16 * MS, 3 * MS)
680 }
681
682 fn records_of(frame: &ProfiledFrame<'_>) -> Vec<&'static str> {
683 frame.records.iter().map(|record| record.name).collect()
684 }
685
686 #[test]
687 fn frames_keep_their_records_and_numbers_up_to_300() {
688 let mut profiler = Profiler::new();
689 assert!(profiler.is_empty());
690 assert_eq!(profiler.frame_rate(), 0.0);
691 let base = Instant::now();
692 for index in 0..PROFILER_FRAMES as u32 + 20 {
693 let start = base + index * 16 * MS;
694 profiler.push(timing(start), &frame_records(start));
695 }
696 assert_eq!(profiler.len(), PROFILER_FRAMES);
697 let indices: Vec<u64> = profiler.frames().map(|frame| frame.index).collect();
698 assert_eq!(indices, (20..320).collect::<Vec<u64>>());
699 let frame = profiler.frame(25).expect("frame 25 is held");
700 assert_eq!(frame.timing.start, base + 25 * 16 * MS);
701 assert_eq!(
702 records_of(&frame),
703 ["player_move", "movement", "nadir::tick", "nadir::render"]
704 );
705 assert_eq!(frame.records[0].start, base + 25 * 16 * MS + 10 * US);
706 assert!(profiler.frame(19).is_none());
707 assert!((profiler.frame_rate() - 62.5).abs() < 0.01);
709 }
710
711 #[test]
712 fn a_frame_of_many_records_drops_the_oldest_frames_and_one_too_many_is_cut() {
713 let mut profiler = Profiler::new();
714 let start = Instant::now();
715 let small = frame_records(start);
716 for _ in 0..10 {
717 profiler.push(timing(start), &small);
718 }
719 let big = vec![record("big", start, US, 0); PROFILER_RECORDS / 2 + 1];
722 profiler.push(timing(start), &big);
723 assert_eq!(profiler.len(), 11);
724 profiler.push(timing(start), &big);
725 let held: Vec<(u64, usize)> = profiler
726 .frames()
727 .map(|frame| (frame.index, frame.records.len()))
728 .collect();
729 assert_eq!(held, [(11, PROFILER_RECORDS / 2 + 1)]);
730
731 let huge = vec![record("huge", start, US, 0); PROFILER_RECORDS + 5];
732 profiler.push(timing(start), &huge);
733 let frame = profiler.frame(12).expect("the huge frame is held");
734 assert_eq!(frame.records.len(), PROFILER_RECORDS);
735 assert_eq!(frame.dropped, 5);
736 assert_eq!(profiler.len(), 1);
737 profiler.push(timing(start), &small);
738 assert_eq!(profiler.len(), 1, "the huge frame filled the pool");
739 assert_eq!(records_of(&profiler.frame(13).expect("held")).len(), 4);
740 }
741
742 fn started(records: &[ScopeRecord]) -> Vec<(&'static str, u32)> {
744 let (mut keys, mut out) = (Vec::new(), Vec::new());
745 start_order(records, &mut keys, &mut out);
746 out.iter()
747 .map(|record| (record.name, record.depth))
748 .collect()
749 }
750
751 #[test]
752 fn scopes_are_put_in_start_order_by_their_nesting_not_their_clock() {
753 let at = Instant::now() + MS;
754 assert_eq!(
756 started(&frame_records(at)),
757 [
758 ("nadir::tick", 0),
759 ("player_move", 1),
760 ("movement", 1),
761 ("nadir::render", 0)
762 ]
763 );
764 let tie = [
767 record("x", at, Duration::ZERO, 0),
768 record("z", at, US, 1),
769 record("y", at, 5 * US, 0),
770 ];
771 assert_eq!(started(&tie), [("x", 0), ("y", 0), ("z", 1)]);
772 let tie = [
775 record("c", at, Duration::ZERO, 1),
776 record("p", at - 5 * US, 5 * US, 0),
777 record("q", at, 3 * US, 0),
778 ];
779 assert_eq!(started(&tie), [("p", 0), ("c", 1), ("q", 0)]);
780 let nested = [
784 record("a1", at, US, 3),
785 record("a", at, US, 2),
786 record("b", at, US, 2),
787 record("p", at, US, 1),
788 record("g", at, US, 0),
789 record("orphan", at, US, 1),
790 ];
791 assert_eq!(
792 started(&nested),
793 [
794 ("g", 0),
795 ("p", 1),
796 ("a", 2),
797 ("a1", 3),
798 ("b", 2),
799 ("orphan", 1)
800 ]
801 );
802 assert!(started(&[]).is_empty());
803 }
804
805 #[test]
806 fn a_paused_profiler_holds_its_frames_and_counts_on() {
807 let mut profiler = Profiler::new();
808 let start = Instant::now();
809 profiler.push(timing(start), &frame_records(start));
810 profiler.set_paused(true);
811 assert!(profiler.paused());
812 for _ in 0..5 {
813 profiler.push(FrameTiming::new(start, 8 * MS, MS), &frame_records(start));
814 }
815 assert_eq!(profiler.len(), 1);
816 profiler.set_paused(false);
817 profiler.push(timing(start), &[]);
818 let indices: Vec<u64> = profiler.frames().map(|frame| frame.index).collect();
819 assert_eq!(indices, [0, 6]);
820 let expected = 7.0 / 0.072;
822 assert!((profiler.frame_rate() - expected).abs() < 0.01);
823 }
824
825 #[test]
826 fn steady_pushes_allocate_nothing() {
827 let mut profiler = Profiler::new();
828 let start = Instant::now();
829 let records = frame_records(start);
830 profiler.push(timing(start), &records);
831 let pool = profiler.records.as_ptr();
832 for _ in 0..PROFILER_FRAMES * 3 {
833 profiler.push(timing(start), &records);
834 }
835 assert_eq!(profiler.records.as_ptr(), pool);
836 assert_eq!(profiler.records.len(), PROFILER_RECORDS);
837 assert!(profiler.slots.capacity() >= PROFILER_FRAMES);
838 assert_eq!(profiler.len(), PROFILER_FRAMES);
839 }
840
841 #[test]
842 fn a_frame_held_takes_its_gpu_time_and_one_not_held_does_not() {
843 let mut profiler = Profiler::new();
844 let start = Instant::now();
845 let gpu = GpuTiming::new(start + MS, 140 * US, 290 * US);
846 assert_eq!(gpu.total(), 430 * US);
847 assert_eq!(profiler.next_index(), 0);
848 assert!(!profiler.set_gpu(0, gpu));
850 for _ in 0..3 {
851 profiler.push(timing(start), &frame_records(start));
852 }
853 assert_eq!(profiler.next_index(), 3);
854 assert!(profiler.set_gpu(1, gpu));
855 let held: Vec<Option<GpuTiming>> = profiler.frames().map(|frame| frame.gpu).collect();
856 assert_eq!(held, [None, Some(gpu), None]);
857 profiler.set_paused(true);
859 profiler.push(timing(start), &frame_records(start));
860 assert_eq!(profiler.next_index(), 4);
861 assert!(!profiler.set_gpu(3, gpu));
862 profiler.set_paused(false);
863 for _ in 0..PROFILER_FRAMES {
864 profiler.push(timing(start), &frame_records(start));
865 }
866 assert!(!profiler.set_gpu(1, gpu));
867 assert!(profiler.frames().all(|frame| frame.gpu.is_none()));
868 let later = GpuTiming::new(start, MS, MS);
870 assert!(profiler.set_gpu(100, gpu));
871 assert!(profiler.set_gpu(100, later));
872 assert_eq!(profiler.frame(100).and_then(|frame| frame.gpu), Some(later));
873 }
874
875 #[derive(Debug)]
878 struct Event {
879 tid: i64,
880 name: String,
881 start: i64,
882 end: i64,
883 }
884
885 fn events(text: &str) -> (Value, Vec<Event>) {
886 let value = json::parse(text, Limits::default()).expect("the trace parses");
887 let list = value
888 .get("traceEvents")
889 .and_then(Value::as_array)
890 .expect("traceEvents is an array")
891 .to_vec();
892 let mut complete = Vec::new();
893 for event in &list {
894 let field = |key: &str| event.get(key).expect(key);
895 assert_eq!(field("pid").as_i64(), Some(PID));
896 let tid = field("tid").as_i64().expect("a track");
897 assert!(tid == TID || tid == GPU_TID, "{event:?}");
898 if field("ph").as_str() == Some("X") {
899 let start = field("ts").as_i64().expect("ts is a whole number");
900 let dur = field("dur").as_i64().expect("dur is a whole number");
901 complete.push(Event {
902 tid,
903 name: field("name").as_str().expect("a name").to_string(),
904 start,
905 end: start + dur,
906 });
907 }
908 }
909 (Value::Array(list), complete)
910 }
911
912 fn depths(events: &[Event]) -> Vec<(String, usize)> {
915 let mut sorted: Vec<&Event> = events.iter().collect();
916 sorted.sort_by(|a, b| a.start.cmp(&b.start).then(b.end.cmp(&a.end)));
917 let mut open: Vec<&Event> = Vec::new();
918 let mut depths = Vec::new();
919 for event in sorted {
920 while open.last().is_some_and(|parent| parent.end <= event.start) {
921 open.pop();
922 }
923 if let Some(parent) = open.last() {
924 assert!(
925 event.end <= parent.end,
926 "{event:?} crosses the end of {parent:?}"
927 );
928 }
929 depths.push((event.name.clone(), open.len()));
930 open.push(event);
931 }
932 depths
933 }
934
935 #[test]
936 fn the_trace_parses_with_every_frame_and_scope_nested() {
937 let mut profiler = Profiler::new();
938 let base = Instant::now();
939 for index in 0..3 {
940 let start = base + index * 16 * MS;
941 profiler.push(timing(start), &frame_records(start));
942 }
943 let (all, complete) = events(&profiler.trace_json());
944 let Value::Array(all) = all else {
945 unreachable!()
946 };
947 assert_eq!(all.len(), 1 + 3 + 3 * 4);
949 assert_eq!(all[0].get("ph").and_then(Value::as_str), Some("M"));
950 assert_eq!(
951 all[0]
952 .get("args")
953 .and_then(|args| args.get("name"))
954 .and_then(Value::as_str),
955 Some("main")
956 );
957 assert_eq!(complete.len(), 3 + 3 * 4);
958 assert!(complete.iter().all(|event| event.tid == TID));
960 let first = &complete[..5];
962 let names: Vec<&str> = first.iter().map(|event| event.name.as_str()).collect();
963 assert_eq!(
964 names,
965 [
966 "frame",
967 "nadir::tick",
968 "player_move",
969 "movement",
970 "nadir::render"
971 ]
972 );
973 assert_eq!((first[0].start, first[0].end), (0, 16_000));
974 assert_eq!((first[1].start, first[1].end), (5, 505));
975 assert_eq!((first[2].start, first[2].end), (10, 110));
976 assert_eq!(complete[5].start, 16_000);
977 assert_eq!(
978 all[1]
979 .get("args")
980 .and_then(|args| args.get("index"))
981 .and_then(Value::as_i64),
982 Some(0)
983 );
984
985 let depths = depths(&complete);
986 let expected = [
987 ("frame", 0),
988 ("nadir::tick", 1),
989 ("player_move", 2),
990 ("movement", 2),
991 ("nadir::render", 1),
992 ];
993 for (index, chunk) in depths.chunks(5).enumerate() {
994 let chunk: Vec<(&str, usize)> = chunk
995 .iter()
996 .map(|(name, depth)| (name.as_str(), *depth))
997 .collect();
998 assert_eq!(chunk, expected, "frame {index}");
999 }
1000 }
1001
1002 #[test]
1003 fn the_gpu_track_places_each_frame_s_passes_after_its_submission_and_the_frame_before() {
1004 let mut profiler = Profiler::new();
1005 let base = Instant::now();
1006 for index in 0..4 {
1007 let start = base + index * 16 * MS;
1008 profiler.push(timing(start), &frame_records(start));
1009 }
1010 let at = |frame: u32, micros: u32| base + frame * 16 * MS + micros * US;
1014 profiler.set_gpu(0, GpuTiming::new(at(0, 600), 300 * US, 700 * US));
1015 profiler.set_gpu(2, GpuTiming::new(at(2, 600), 15 * MS, 5 * MS));
1016 profiler.set_gpu(3, GpuTiming::new(at(3, 600), 100 * US, 200 * US));
1017 let (all, complete) = events(&profiler.trace_json());
1018 let Value::Array(all) = all else {
1019 unreachable!()
1020 };
1021 let arg =
1022 |event: &Value, key: &str| event.get("args").and_then(|args| args.get(key)).cloned();
1023 let names: Vec<(Option<i64>, Option<Value>)> = all
1024 .iter()
1025 .filter(|event| event.get("ph").and_then(Value::as_str) == Some("M"))
1026 .map(|event| (event.get("tid").and_then(Value::as_i64), arg(event, "name")))
1027 .collect();
1028 let name = |text: &str| Some(Value::String(text.to_string()));
1029 assert_eq!(
1030 names,
1031 [(Some(TID), name("main")), (Some(GPU_TID), name("gpu"))]
1032 );
1033
1034 let gpu: Vec<(&str, i64, i64)> = complete
1035 .iter()
1036 .filter(|event| event.tid == GPU_TID)
1037 .map(|event| (event.name.as_str(), event.start, event.end))
1038 .collect();
1039 assert_eq!(
1040 gpu,
1041 [
1042 ("frame", 600, 1_600),
1043 ("world", 600, 900),
1044 ("output", 900, 1_600),
1045 ("frame", 32_600, 52_600),
1046 ("world", 32_600, 47_600),
1047 ("output", 47_600, 52_600),
1048 ("frame", 52_600, 52_900),
1050 ("world", 52_600, 52_700),
1051 ("output", 52_700, 52_900),
1052 ]
1053 );
1054 let frames: Vec<(Option<i64>, Option<f64>)> = all
1055 .iter()
1056 .filter(|event| {
1057 event.get("tid").and_then(Value::as_i64) == Some(GPU_TID)
1058 && event.get("name").and_then(Value::as_str) == Some("frame")
1059 })
1060 .map(|event| {
1061 let index = arg(event, "index").and_then(|value| value.as_i64());
1062 (index, arg(event, "gpu_ms").and_then(|value| value.as_f64()))
1063 })
1064 .collect();
1065 assert_eq!(
1066 frames,
1067 [
1068 (Some(0), Some(1.0)),
1069 (Some(2), Some(20.0)),
1070 (Some(3), Some(0.3))
1071 ]
1072 );
1073
1074 let (cpu, gpu): (Vec<Event>, Vec<Event>) =
1077 complete.into_iter().partition(|event| event.tid == TID);
1078 assert_eq!(cpu.len(), 4 + 4 * 4);
1079 depths(&cpu);
1080 let nested: Vec<(String, usize)> = depths(&gpu);
1081 let expected = [("frame", 0), ("world", 1), ("output", 1)].repeat(3);
1082 let nested: Vec<(&str, usize)> = nested
1083 .iter()
1084 .map(|(name, depth)| (name.as_str(), *depth))
1085 .collect();
1086 assert_eq!(nested, expected);
1087 }
1088
1089 #[test]
1090 fn times_between_microseconds_keep_scopes_nested_and_frames_meeting() {
1091 const NS: Duration = Duration::from_nanos(1);
1092 let length = 16_666_667 * NS;
1095 let mut profiler = Profiler::new();
1096 let base = Instant::now();
1097 for index in 0..4 {
1098 let start = base + index * length;
1099 let records = [
1100 record("child", start + 900 * NS, 300 * NS, 1),
1101 record("parent", start + 400 * NS, 1_200 * NS, 0),
1102 ];
1103 profiler.push(FrameTiming::new(start, length, MS), &records);
1104 }
1105 let (_, complete) = events(&profiler.trace_json());
1106 let frames: Vec<(i64, i64)> = complete
1107 .iter()
1108 .filter(|event| event.name == "frame")
1109 .map(|event| (event.start, event.end))
1110 .collect();
1111 assert_eq!(
1112 frames,
1113 [
1114 (0, 16_666),
1115 (16_666, 33_333),
1116 (33_333, 50_000),
1117 (50_000, 66_666)
1118 ]
1119 );
1120 depths(&complete);
1122 for (index, chunk) in complete.chunks(3).enumerate() {
1124 let [frame, parent, child] = chunk else {
1125 panic!("three events a frame");
1126 };
1127 assert_eq!(
1128 (
1129 frame.name.as_str(),
1130 parent.name.as_str(),
1131 child.name.as_str()
1132 ),
1133 ("frame", "parent", "child")
1134 );
1135 for (outer, inner) in [(frame, parent), (parent, child)] {
1136 assert!(
1137 outer.start <= inner.start && inner.end <= outer.end,
1138 "frame {index}: {inner:?} is not inside {outer:?}"
1139 );
1140 }
1141 }
1142 assert_eq!((complete[7].start, complete[7].end), (33_333, 33_334));
1145 assert_eq!((complete[8].start, complete[8].end), (33_334, 33_334));
1146 }
1147
1148 #[test]
1149 fn an_empty_profiler_writes_a_trace_of_the_thread_name_alone() {
1150 let (all, complete) = events(&Profiler::new().trace_json());
1151 assert_eq!(all.as_array().map(<[Value]>::len), Some(1));
1152 assert!(complete.is_empty());
1153 }
1154
1155 #[test]
1156 fn names_are_escaped_and_a_scope_before_the_first_frame_starts_at_0() {
1157 let mut profiler = Profiler::new();
1158 let base = Instant::now() + MS;
1159 let records = [record("say \"hi\"\n", base - MS, 2 * MS, 0)];
1160 profiler.push(timing(base), &records);
1161 let (_, complete) = events(&profiler.trace_json());
1162 assert_eq!(complete[1].name, "say \"hi\"\n");
1163 assert_eq!((complete[1].start, complete[1].end), (0, 1000));
1165 }
1166}