Skip to main content

nadir_debug/
profiler.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The profiler: the last frames' timings and scopes in a ring, with the
16//! GPU's time over each frame's drawing once it is read back; their graphs
17//! and a frame's scope tree in a window; and the Chrome trace of them
18//! (`debug-tools.md`, "Profiler").
19
20use 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
30/// The frames a [`Profiler`] keeps: five seconds at 60 frames a second.
31pub const PROFILER_FRAMES: usize = 300;
32
33/// The scope records a [`Profiler`] keeps, of all its frames together: a
34/// frame of many records leaves room for fewer frames, and one of more
35/// than this keeps this many.
36pub const PROFILER_RECORDS: usize = 32_768;
37
38/// The frames whose lengths [`Profiler::frame_rate`] averages.
39const RATE_FRAMES: usize = 60;
40
41/// The top of the graph: two frames at 60 a second. A frame that took
42/// longer is drawn at the top.
43const GRAPH_TOP_MS: f32 = 1000.0 / 30.0;
44
45/// The graph's height, in UI units.
46const GRAPH_HEIGHT: f32 = 60.0;
47
48/// The trace's process and thread.
49const PID: i64 = 1;
50const TID: i64 = 1;
51
52/// The trace's track of the GPU's passes.
53const GPU_TID: i64 = 2;
54
55/// When a frame started, and how long it took.
56#[non_exhaustive]
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub struct FrameTiming {
59    /// When the frame started.
60    pub start: Instant,
61    /// How long it was: until the next frame started.
62    pub length: Duration,
63    /// How long the processor worked on it: its length less the waits,
64    /// such as the frame limiter's sleep and the display's swap.
65    pub work: Duration,
66}
67
68impl FrameTiming {
69    /// A frame that started at `start`, `length` long, `work` of which the
70    /// processor worked on it.
71    pub fn new(start: Instant, length: Duration, work: Duration) -> Self {
72        Self {
73            start,
74            length,
75            work,
76        }
77    }
78}
79
80/// The GPU's time over a frame's drawing: each of the renderer's passes,
81/// as its timers measured them, read back frames later
82/// ([`Profiler::set_gpu`]).
83#[non_exhaustive]
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85pub struct GpuTiming {
86    /// When the processor started the drawing: the GPU started timing its
87    /// passes later, no sooner than the renderer began timing the world
88    /// pass. The timers measure how long, not when, so the trace places
89    /// the passes from here.
90    pub submitted: Instant,
91    /// The world pass: the world drawn into the virtual image.
92    pub world: Duration,
93    /// The output pass: the virtual image onto the window, then the UI.
94    pub output: Duration,
95}
96
97impl GpuTiming {
98    /// A drawing started at `submitted`, whose passes took the GPU `world`
99    /// and `output`.
100    pub fn new(submitted: Instant, world: Duration, output: Duration) -> Self {
101        Self {
102            submitted,
103            world,
104            output,
105        }
106    }
107
108    /// The passes' times together.
109    pub fn total(&self) -> Duration {
110        self.world + self.output
111    }
112}
113
114/// A frame the profiler holds.
115#[non_exhaustive]
116#[derive(Clone, Copy, Debug)]
117pub struct ProfiledFrame<'a> {
118    /// Its number: the frames pushed before it, paused or not.
119    pub index: u64,
120    /// When it started and how long it took.
121    pub timing: FrameTiming,
122    /// The GPU's time over its drawing, once read back: `None` until then,
123    /// and for a frame not drawn or not timed.
124    pub gpu: Option<GpuTiming>,
125    /// Its scopes, in the order they ended, so that a parent follows its
126    /// children.
127    pub records: &'a [ScopeRecord],
128    /// Its scopes not kept: those past [`PROFILER_RECORDS`].
129    pub dropped: usize,
130}
131
132/// What the profiler's window did this frame.
133#[non_exhaustive]
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
135pub struct ProfilerResponse {
136    /// "Write trace" was clicked: the caller writes
137    /// [`Profiler::trace_json`] to a file, and says where with
138    /// [`Profiler::set_note`].
139    pub write_trace: bool,
140}
141
142/// A frame in the ring: where its records are in the pool.
143#[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
159/// The last [`PROFILER_FRAMES`] frames' timings and scopes, which
160/// [`Profiler::show`] draws as graphs of each frame's processor time and
161/// GPU time and, for the frame clicked, its scopes as a tree, and
162/// [`Profiler::trace_json`] writes as a Chrome trace.
163///
164/// The engine pushes each frame with the scopes that
165/// `nadir_core::profile::take_frame` collected, and gives a frame it held
166/// the GPU's time over its drawing when that is read back, frames later
167/// ([`Profiler::set_gpu`]). The records of all the frames share one pool
168/// of [`PROFILER_RECORDS`], made at the first push: a push after that
169/// allocates nothing. While paused, it keeps what it holds, and counts the
170/// frames and their rate on.
171pub struct Profiler {
172    slots: VecDeque<Slot>,
173    /// The frames' records, each frame's in one run: empty until the first
174    /// push.
175    records: Vec<ScopeRecord>,
176    /// Where the next frame's records go.
177    head: usize,
178    /// The next frame's number.
179    next: u64,
180    /// The last frames' lengths, for the frame rate.
181    lengths: [Duration; RATE_FRAMES],
182    rate_next: usize,
183    rate_count: usize,
184    paused: bool,
185    selected: Option<u64>,
186    /// The selected frame's records in the order they started, as the tree
187    /// shows them, and the keys that put them in it.
188    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    /// A profiler holding no frame, not paused.
201    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    /// Adds a frame, with its scopes, and drops the oldest frames to make
219    /// room for it. While paused, it only counts the frame and its length.
220    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    /// The number the next frame pushed gets: the frames pushed so far,
266    /// paused or not. While a frame runs, before it is pushed, its own.
267    pub fn next_index(&self) -> u64 {
268        self.next
269    }
270
271    /// Gives the frame numbered `index` the GPU's time over its drawing,
272    /// which the GPU's timers give frames after the frame is pushed.
273    /// Returns whether it holds that frame: a frame dropped, or pushed
274    /// while paused, keeps nothing.
275    pub fn set_gpu(&mut self, index: u64, timing: GpuTiming) -> bool {
276        // The frame is one of the last few: look from the newest.
277        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    /// How many frames it holds.
287    pub fn len(&self) -> usize {
288        self.slots.len()
289    }
290
291    /// Whether it holds no frame.
292    pub fn is_empty(&self) -> bool {
293        self.slots.is_empty()
294    }
295
296    /// The frames it holds, the oldest first.
297    pub fn frames(&self) -> impl ExactSizeIterator<Item = ProfiledFrame<'_>> + '_ {
298        self.slots.iter().map(|slot| self.view(slot))
299    }
300
301    /// The frame numbered `index`, if it holds it.
302    pub fn frame(&self, index: u64) -> Option<ProfiledFrame<'_>> {
303        self.slot(index).map(|slot| self.view(slot))
304    }
305
306    /// The frames a second, over the last 60 frames pushed, paused or not:
307    /// 0 before the first, or while they take no time.
308    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    /// Whether it is paused: holding its frames while the game runs on.
318    pub fn paused(&self) -> bool {
319        self.paused
320    }
321
322    /// Pauses it, or lets it record again.
323    pub fn set_paused(&mut self, paused: bool) {
324        self.paused = paused;
325    }
326
327    /// The number of the frame whose scopes the window shows, if any.
328    pub fn selected(&self) -> Option<u64> {
329        self.selected
330    }
331
332    /// Shows the scopes of the frame numbered `index`, or of none.
333    pub fn select(&mut self, index: Option<u64>) {
334        self.selected = index;
335    }
336
337    /// Sets the line the window shows under its buttons, such as where a
338    /// trace was written; an empty one shows nothing.
339    pub fn set_note(&mut self, note: impl fmt::Display) {
340        self.note.clear();
341        // Writing to a `String` cannot fail.
342        let _ = write!(self.note, "{note}");
343    }
344
345    /// Fills a window: a checkbox that pauses it, a "Write trace" button,
346    /// the note, graphs of each frame's processor time and of its GPU time
347    /// on one scale, 0 to 33 ms (the oldest on the left, a frame with no
348    /// GPU time a gap), which say the frame under the pointer and select
349    /// the one clicked, and the selected frame's GPU passes, and its scopes
350    /// as a tree, each with how long it took.
351    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        // A NaN is a gap: a frame whose GPU time is not known.
371        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    /// The frames it holds as Chrome trace event JSON, which Perfetto UI
436    /// and `chrome://tracing` open: `{"traceEvents": [...]}`, a name for
437    /// the thread, `main`, then for each frame a complete event
438    /// (`"ph": "X"`) named `frame`, with its number and processor time as
439    /// arguments, and one for each of its scopes, in the order they
440    /// started, a parent before its children.
441    ///
442    /// When a frame it holds has its GPU time, a second track, named
443    /// `gpu`, holds for each such frame an event `frame`, with its number
444    /// and GPU time as arguments, over its passes, `world` then `output`.
445    /// The GPU's timers measure how long, not when: each frame's passes
446    /// are placed one after the other from when its drawing started, or
447    /// from the end of the frame before on the track if that is later, as
448    /// a GPU does one frame's work after another's. So their lengths are
449    /// the GPU's, and where they start an estimate. Taking the timers'
450    /// times as exact, a frame's start is never before its drawing
451    /// started, nor after the GPU started its world pass's timer; a frame
452    /// placed from its drawing's start is early by at least the time until
453    /// the renderer began timing its world pass, and one placed after the
454    /// frame before by at least as much as that one, less up to a
455    /// microsecond for the rounding below.
456    ///
457    /// Times are whole microseconds from the oldest frame's start, each
458    /// start and end rounded down, so that, for a reader that converts
459    /// them to nanoseconds, a scope stays inside its parent's event, two
460    /// in a row never overlap, and a frame ends where the next starts,
461    /// exactly. A scope shorter than a microsecond may become an instant,
462    /// which at its parent's end a reader may show beside it. A scope that
463    /// started before the oldest frame starts at 0, and ends where it
464    /// ended.
465    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        // When the GPU is done with the frames placed so far.
481        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            // The output pass starts where the world pass ends, each
509            // instant rounded alike, so that they meet inside the frame.
510            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
537/// Shows `records`, sorted by when they started, as a tree: each a node
538/// whose children are the records after it that are deeper, up to the
539/// next one that is not; a record with no children a line.
540fn 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            // Its place among its siblings keeps a node open from frame to
554            // frame, and apart from a sibling of its name.
555            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
565/// Where a record's run of descendants begins in the order they ended, its
566/// depth, and its own place there.
567type OrderKey = (u32, u32, u32);
568
569/// Puts `records`, in the order they ended, into `out` in the order they
570/// started: each parent before its children, siblings in their order.
571///
572/// In the order they ended, a record follows its descendants, which are
573/// the run of deeper records just before it. So the record before a run is
574/// the root of a child's, whose own run begins where its key says: each
575/// record finds where its run begins by stepping back over its children.
576/// Sorted by that, then by depth, a parent comes before its first child,
577/// and a sibling after the runs before it. Start times would not do: two
578/// scopes may start on the same tick of a coarse clock (100 ns on
579/// Windows), and no tie-break orders both a parent and a sibling right.
580/// `keys` is a buffer the calls reuse.
581fn 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 - 1` ends a child's run: step back over all of it.
587            first = keys[first - 1].0 as usize;
588        }
589        // A frame holds at most `PROFILER_RECORDS` records, so these fit.
590        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
605/// Whole microseconds, rounded down.
606fn 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
619/// The metadata event (`"ph": "M"`) that names the track `tid`.
620fn 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
633/// A complete event (`"ph": "X"`) on the track `tid`.
634fn 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    /// A frame at `start` of a tick with two systems, then a draw, as the
668    /// recorder gives them: in the order they ended.
669    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        // 60 frames of 16 ms each.
708        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        // Half the pool, twice: the second wraps to the pool's start, over
720        // the small frames and the first big one.
721        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    /// The names and depths of `records` in the order they started.
743    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        // As the recorder gives them, in the order they ended.
755        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        // Siblings started on one tick of the clock: `x` ended before `y`
765        // began, so `z` is `y`'s, though `y` is the longer.
766        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        // A last child and the next sibling of its parent started on one
773        // tick: `c` is `p`'s.
774        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        // Deep nesting, a parent of two children with their own, and the
781        // children of a scope still open when the frame was collected,
782        // whose parent is in the next frame.
783        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        // The frames while paused count in the rate: 16, 8 × 5, 16 ms.
821        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        // Not pushed yet: the frame being run.
849        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        // A frame pushed while paused is not held, nor one dropped.
858        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        // Given again, the later time stands.
869        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    /// An event of the parsed trace: its track, its name, and when it
876    /// starts and ends.
877    #[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    /// The depth of each event: how many events enclose it, each one wholly
913    /// inside the one that encloses it, and none crossing another.
914    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        // The thread's name, then 3 frames of 4 scopes each.
948        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        // No frame has a GPU time: no GPU track.
959        assert!(complete.iter().all(|event| event.tid == TID));
960        // Each frame, then its scopes in the order they started.
961        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        // Frame 0 drawn 600 µs in, 1 ms on the GPU; frame 1 with no time;
1011        // frame 2's 20 ms on the GPU past frame 3's submission, which then
1012        // waits for it.
1013        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                // Submitted at 48,600: after frame 2's passes, at 52,600.
1049                ("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        // Each track nests on its own: the processor's as before, and the
1075        // GPU's frames each over its two passes.
1076        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        // Frames of 16,666,667 ns; a parent from 0.4 to 1.6 µs into each,
1093        // and its child from 0.9 to 1.2 µs, both inside it.
1094        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        // None crosses another's end.
1121        depths(&complete);
1122        // Each frame, then its parent and child, each inside the one before.
1123        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        // In the third frame the child, shorter than a microsecond, ends
1143        // up at the end of its parent, as an instant.
1144        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        // It started 1 ms before the oldest frame, and ran for 2 ms.
1164        assert_eq!((complete[1].start, complete[1].end), (0, 1000));
1165    }
1166}