use std::collections::VecDeque;
use std::fmt::{self, Write as _};
use std::ops::Range;
use std::time::{Duration, Instant};
use nadir_codec::json::{self, Value};
use nadir_core::profile::ScopeRecord;
use crate::{Plot, Ui};
pub const PROFILER_FRAMES: usize = 300;
pub const PROFILER_RECORDS: usize = 32_768;
const RATE_FRAMES: usize = 60;
const GRAPH_TOP_MS: f32 = 1000.0 / 30.0;
const GRAPH_HEIGHT: f32 = 60.0;
const PID: i64 = 1;
const TID: i64 = 1;
const GPU_TID: i64 = 2;
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FrameTiming {
pub start: Instant,
pub length: Duration,
pub work: Duration,
}
impl FrameTiming {
pub fn new(start: Instant, length: Duration, work: Duration) -> Self {
Self {
start,
length,
work,
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GpuTiming {
pub submitted: Instant,
pub world: Duration,
pub output: Duration,
}
impl GpuTiming {
pub fn new(submitted: Instant, world: Duration, output: Duration) -> Self {
Self {
submitted,
world,
output,
}
}
pub fn total(&self) -> Duration {
self.world + self.output
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
pub struct ProfiledFrame<'a> {
pub index: u64,
pub timing: FrameTiming,
pub gpu: Option<GpuTiming>,
pub records: &'a [ScopeRecord],
pub dropped: usize,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ProfilerResponse {
pub write_trace: bool,
}
#[derive(Clone, Copy, Debug)]
struct Slot {
index: u64,
timing: FrameTiming,
gpu: Option<GpuTiming>,
first: usize,
len: usize,
dropped: usize,
}
impl Slot {
fn range(&self) -> Range<usize> {
self.first..self.first + self.len
}
}
pub struct Profiler {
slots: VecDeque<Slot>,
records: Vec<ScopeRecord>,
head: usize,
next: u64,
lengths: [Duration; RATE_FRAMES],
rate_next: usize,
rate_count: usize,
paused: bool,
selected: Option<u64>,
order: Vec<ScopeRecord>,
keys: Vec<OrderKey>,
note: String,
}
impl Default for Profiler {
fn default() -> Self {
Self::new()
}
}
impl Profiler {
pub fn new() -> Self {
Self {
slots: VecDeque::with_capacity(PROFILER_FRAMES),
records: Vec::new(),
head: 0,
next: 0,
lengths: [Duration::ZERO; RATE_FRAMES],
rate_next: 0,
rate_count: 0,
paused: false,
selected: None,
order: Vec::new(),
keys: Vec::new(),
note: String::new(),
}
}
pub fn push(&mut self, timing: FrameTiming, records: &[ScopeRecord]) {
self.lengths[self.rate_next] = timing.length;
self.rate_next = (self.rate_next + 1) % RATE_FRAMES;
self.rate_count = (self.rate_count + 1).min(RATE_FRAMES);
let index = self.next;
self.next += 1;
if self.paused {
return;
}
if self.records.is_empty() {
let blank = ScopeRecord {
name: "",
start: timing.start,
duration: Duration::ZERO,
depth: 0,
};
self.records = vec![blank; PROFILER_RECORDS];
}
let len = records.len().min(PROFILER_RECORDS);
let first = if self.head + len > PROFILER_RECORDS {
0
} else {
self.head
};
let range = first..first + len;
while self.slots.len() == PROFILER_FRAMES
|| self
.slots
.iter()
.any(|slot| overlaps(&slot.range(), &range))
{
self.slots.pop_front();
}
self.records[range].copy_from_slice(&records[..len]);
self.head = first + len;
self.slots.push_back(Slot {
index,
timing,
gpu: None,
first,
len,
dropped: records.len() - len,
});
}
pub fn next_index(&self) -> u64 {
self.next
}
pub fn set_gpu(&mut self, index: u64, timing: GpuTiming) -> bool {
match self.slots.iter_mut().rev().find(|slot| slot.index == index) {
Some(slot) => {
slot.gpu = Some(timing);
true
}
None => false,
}
}
pub fn len(&self) -> usize {
self.slots.len()
}
pub fn is_empty(&self) -> bool {
self.slots.is_empty()
}
pub fn frames(&self) -> impl ExactSizeIterator<Item = ProfiledFrame<'_>> + '_ {
self.slots.iter().map(|slot| self.view(slot))
}
pub fn frame(&self, index: u64) -> Option<ProfiledFrame<'_>> {
self.slot(index).map(|slot| self.view(slot))
}
pub fn frame_rate(&self) -> f32 {
let total: Duration = self.lengths[..self.rate_count].iter().sum();
if total.is_zero() {
0.0
} else {
self.rate_count as f32 / total.as_secs_f32()
}
}
pub fn paused(&self) -> bool {
self.paused
}
pub fn set_paused(&mut self, paused: bool) {
self.paused = paused;
}
pub fn selected(&self) -> Option<u64> {
self.selected
}
pub fn select(&mut self, index: Option<u64>) {
self.selected = index;
}
pub fn set_note(&mut self, note: impl fmt::Display) {
self.note.clear();
let _ = write!(self.note, "{note}");
}
pub fn show(&mut self, ui: &mut Ui<'_>) -> ProfilerResponse {
let mut response = ProfilerResponse::default();
ui.horizontal(|ui| {
ui.checkbox("Paused", &mut self.paused);
response.write_trace = ui.button("Write trace").clicked;
});
if !self.note.is_empty() {
ui.label(&self.note);
}
let selected = self
.selected
.and_then(|index| self.slots.iter().position(|slot| slot.index == index));
let plot = Plot {
range: 0.0..=GRAPH_TOP_MS,
height: GRAPH_HEIGHT,
selected,
};
let values = self.slots.iter().map(|slot| millis(slot.timing.work));
let cpu = ui.plot("CPU ms##graph", values, plot.clone());
let values = self
.slots
.iter()
.map(|slot| slot.gpu.map_or(f32::NAN, |gpu| millis(gpu.total())));
let gpu = ui.plot("GPU ms##gpu", values, plot);
let clicked = cpu.clicked.or(gpu.clicked);
if let Some(slot) = clicked.and_then(|at| self.slots.get(at)) {
self.selected = Some(slot.index);
}
let hovered = cpu.hovered.or(gpu.hovered);
match hovered.and_then(|at| self.slots.get(at)) {
Some(slot) => match slot.gpu {
Some(gpu) => ui.label(format_args!(
"frame {}: {:.2} ms CPU, {:.2} ms GPU, {:.2} ms long",
slot.index,
millis(slot.timing.work),
millis(gpu.total()),
millis(slot.timing.length)
)),
None => ui.label(format_args!(
"frame {}: {:.2} ms CPU, {:.2} ms long",
slot.index,
millis(slot.timing.work),
millis(slot.timing.length)
)),
},
None => ui.label(format_args!(
"{} frames, {:.0} a second",
self.slots.len(),
self.frame_rate()
)),
}
ui.separator();
let Some(index) = self.selected else {
ui.label("Click a frame for its scopes.");
return response;
};
let Some(&slot) = self.slot(index) else {
ui.label(format_args!("Frame {index} is gone: click another."));
return response;
};
ui.label(format_args!(
"frame {}: {} scopes, {:.3} ms CPU",
slot.index,
slot.len,
millis(slot.timing.work)
));
if slot.dropped > 0 {
ui.label(format_args!("{} more scopes not kept", slot.dropped));
}
match slot.gpu {
Some(gpu) => ui.label(format_args!(
"GPU {:.3} ms: world {:.3}, output {:.3}",
millis(gpu.total()),
millis(gpu.world),
millis(gpu.output)
)),
None => ui.label("no GPU time"),
}
start_order(&self.records[slot.range()], &mut self.keys, &mut self.order);
tree(ui, &self.order);
response
}
pub fn trace_json(&self) -> String {
let origin = self.slots.front().map(|slot| slot.timing.start);
let since =
|at: Instant| origin.map_or(0, |origin| micros(at.saturating_duration_since(origin)));
let span = |start: Instant, duration: Duration| {
let ts = since(start);
(ts, since(start + duration) - ts)
};
let timed = self.slots.iter().filter(|slot| slot.gpu.is_some()).count();
let mut events = Vec::with_capacity(2 + self.slots.len() + self.records_held() + 3 * timed);
let (mut keys, mut ordered) = (Vec::new(), Vec::new());
events.push(thread_name(TID, "main"));
if timed > 0 {
events.push(thread_name(GPU_TID, "gpu"));
}
let mut gpu_free: Option<Instant> = None;
for frame in self.frames() {
let index = i64::try_from(frame.index).unwrap_or(i64::MAX);
let cpu_ms = micros(frame.timing.work) as f64 / 1000.0;
let args = object(vec![
("index", Value::Int(index)),
("cpu_ms", Value::Float(cpu_ms)),
]);
let (ts, dur) = span(frame.timing.start, frame.timing.length);
events.push(complete(TID, "frame", ts, dur, Some(args)));
start_order(frame.records, &mut keys, &mut ordered);
for record in &ordered {
let (ts, dur) = span(record.start, record.duration);
events.push(complete(TID, record.name, ts, dur, None));
}
let Some(gpu) = frame.gpu else {
continue;
};
let start = gpu_free.map_or(gpu.submitted, |free| free.max(gpu.submitted));
let between = start + gpu.world;
let end = between + gpu.output;
gpu_free = Some(end);
let gpu_ms = micros(gpu.total()) as f64 / 1000.0;
let args = object(vec![
("index", Value::Int(index)),
("gpu_ms", Value::Float(gpu_ms)),
]);
let (start, between, end) = (since(start), since(between), since(end));
events.push(complete(GPU_TID, "frame", start, end - start, Some(args)));
events.push(complete(GPU_TID, "world", start, between - start, None));
events.push(complete(GPU_TID, "output", between, end - between, None));
}
json::to_string_compact(&object(vec![("traceEvents", Value::Array(events))]))
}
fn records_held(&self) -> usize {
self.slots.iter().map(|slot| slot.len).sum()
}
fn slot(&self, index: u64) -> Option<&Slot> {
self.slots.iter().find(|slot| slot.index == index)
}
fn view(&self, slot: &Slot) -> ProfiledFrame<'_> {
ProfiledFrame {
index: slot.index,
timing: slot.timing,
gpu: slot.gpu,
records: &self.records[slot.range()],
dropped: slot.dropped,
}
}
}
fn tree(ui: &mut Ui<'_>, records: &[ScopeRecord]) {
let mut at = 0;
let mut position = 0_usize;
while let Some(record) = records.get(at) {
let deeper = records[at + 1..]
.iter()
.take_while(|child| child.depth > record.depth)
.count();
let children = &records[at + 1..at + 1 + deeper];
let ms = f64::from(millis(record.duration));
if children.is_empty() {
ui.label(format_args!(" {} {ms:.3} ms", record.name));
} else {
ui.tree_node(
format_args!("{} {ms:.3} ms##{position}:{}", record.name, record.name),
|ui| tree(ui, children),
);
}
at += 1 + deeper;
position += 1;
}
}
type OrderKey = (u32, u32, u32);
fn start_order(records: &[ScopeRecord], keys: &mut Vec<OrderKey>, out: &mut Vec<ScopeRecord>) {
keys.clear();
for (index, record) in records.iter().enumerate() {
let mut first = index;
while first > 0 && records[first - 1].depth > record.depth {
first = keys[first - 1].0 as usize;
}
keys.push((first as u32, record.depth, index as u32));
}
keys.sort_unstable();
out.clear();
out.extend(keys.iter().map(|&(_, _, index)| records[index as usize]));
}
fn overlaps(a: &Range<usize>, b: &Range<usize>) -> bool {
a.start < b.end && b.start < a.end
}
fn millis(duration: Duration) -> f32 {
duration.as_secs_f32() * 1000.0
}
fn micros(duration: Duration) -> i64 {
i64::try_from(duration.as_micros()).unwrap_or(i64::MAX)
}
fn object(members: Vec<(&str, Value)>) -> Value {
Value::Object(
members
.into_iter()
.map(|(key, value)| (key.to_string(), value))
.collect(),
)
}
fn thread_name(tid: i64, name: &str) -> Value {
object(vec![
("name", Value::String("thread_name".to_string())),
("ph", Value::String("M".to_string())),
("pid", Value::Int(PID)),
("tid", Value::Int(tid)),
(
"args",
object(vec![("name", Value::String(name.to_string()))]),
),
])
}
fn complete(tid: i64, name: &str, ts: i64, dur: i64, args: Option<Value>) -> Value {
let mut members = vec![
("name", Value::String(name.to_string())),
("ph", Value::String("X".to_string())),
("ts", Value::Int(ts)),
("dur", Value::Int(dur)),
("pid", Value::Int(PID)),
("tid", Value::Int(tid)),
];
if let Some(args) = args {
members.push(("args", args));
}
object(members)
}
#[cfg(test)]
mod tests {
use nadir_codec::Limits;
use super::*;
const MS: Duration = Duration::from_millis(1);
const US: Duration = Duration::from_micros(1);
fn record(name: &'static str, start: Instant, duration: Duration, depth: u32) -> ScopeRecord {
ScopeRecord {
name,
start,
duration,
depth,
}
}
fn frame_records(start: Instant) -> Vec<ScopeRecord> {
vec![
record("player_move", start + 10 * US, 100 * US, 1),
record("movement", start + 120 * US, 300 * US, 1),
record("nadir::tick", start + 5 * US, 500 * US, 0),
record("nadir::render", start + 600 * US, 2 * MS, 0),
]
}
fn timing(start: Instant) -> FrameTiming {
FrameTiming::new(start, 16 * MS, 3 * MS)
}
fn records_of(frame: &ProfiledFrame<'_>) -> Vec<&'static str> {
frame.records.iter().map(|record| record.name).collect()
}
#[test]
fn frames_keep_their_records_and_numbers_up_to_300() {
let mut profiler = Profiler::new();
assert!(profiler.is_empty());
assert_eq!(profiler.frame_rate(), 0.0);
let base = Instant::now();
for index in 0..PROFILER_FRAMES as u32 + 20 {
let start = base + index * 16 * MS;
profiler.push(timing(start), &frame_records(start));
}
assert_eq!(profiler.len(), PROFILER_FRAMES);
let indices: Vec<u64> = profiler.frames().map(|frame| frame.index).collect();
assert_eq!(indices, (20..320).collect::<Vec<u64>>());
let frame = profiler.frame(25).expect("frame 25 is held");
assert_eq!(frame.timing.start, base + 25 * 16 * MS);
assert_eq!(
records_of(&frame),
["player_move", "movement", "nadir::tick", "nadir::render"]
);
assert_eq!(frame.records[0].start, base + 25 * 16 * MS + 10 * US);
assert!(profiler.frame(19).is_none());
assert!((profiler.frame_rate() - 62.5).abs() < 0.01);
}
#[test]
fn a_frame_of_many_records_drops_the_oldest_frames_and_one_too_many_is_cut() {
let mut profiler = Profiler::new();
let start = Instant::now();
let small = frame_records(start);
for _ in 0..10 {
profiler.push(timing(start), &small);
}
let big = vec![record("big", start, US, 0); PROFILER_RECORDS / 2 + 1];
profiler.push(timing(start), &big);
assert_eq!(profiler.len(), 11);
profiler.push(timing(start), &big);
let held: Vec<(u64, usize)> = profiler
.frames()
.map(|frame| (frame.index, frame.records.len()))
.collect();
assert_eq!(held, [(11, PROFILER_RECORDS / 2 + 1)]);
let huge = vec![record("huge", start, US, 0); PROFILER_RECORDS + 5];
profiler.push(timing(start), &huge);
let frame = profiler.frame(12).expect("the huge frame is held");
assert_eq!(frame.records.len(), PROFILER_RECORDS);
assert_eq!(frame.dropped, 5);
assert_eq!(profiler.len(), 1);
profiler.push(timing(start), &small);
assert_eq!(profiler.len(), 1, "the huge frame filled the pool");
assert_eq!(records_of(&profiler.frame(13).expect("held")).len(), 4);
}
fn started(records: &[ScopeRecord]) -> Vec<(&'static str, u32)> {
let (mut keys, mut out) = (Vec::new(), Vec::new());
start_order(records, &mut keys, &mut out);
out.iter()
.map(|record| (record.name, record.depth))
.collect()
}
#[test]
fn scopes_are_put_in_start_order_by_their_nesting_not_their_clock() {
let at = Instant::now() + MS;
assert_eq!(
started(&frame_records(at)),
[
("nadir::tick", 0),
("player_move", 1),
("movement", 1),
("nadir::render", 0)
]
);
let tie = [
record("x", at, Duration::ZERO, 0),
record("z", at, US, 1),
record("y", at, 5 * US, 0),
];
assert_eq!(started(&tie), [("x", 0), ("y", 0), ("z", 1)]);
let tie = [
record("c", at, Duration::ZERO, 1),
record("p", at - 5 * US, 5 * US, 0),
record("q", at, 3 * US, 0),
];
assert_eq!(started(&tie), [("p", 0), ("c", 1), ("q", 0)]);
let nested = [
record("a1", at, US, 3),
record("a", at, US, 2),
record("b", at, US, 2),
record("p", at, US, 1),
record("g", at, US, 0),
record("orphan", at, US, 1),
];
assert_eq!(
started(&nested),
[
("g", 0),
("p", 1),
("a", 2),
("a1", 3),
("b", 2),
("orphan", 1)
]
);
assert!(started(&[]).is_empty());
}
#[test]
fn a_paused_profiler_holds_its_frames_and_counts_on() {
let mut profiler = Profiler::new();
let start = Instant::now();
profiler.push(timing(start), &frame_records(start));
profiler.set_paused(true);
assert!(profiler.paused());
for _ in 0..5 {
profiler.push(FrameTiming::new(start, 8 * MS, MS), &frame_records(start));
}
assert_eq!(profiler.len(), 1);
profiler.set_paused(false);
profiler.push(timing(start), &[]);
let indices: Vec<u64> = profiler.frames().map(|frame| frame.index).collect();
assert_eq!(indices, [0, 6]);
let expected = 7.0 / 0.072;
assert!((profiler.frame_rate() - expected).abs() < 0.01);
}
#[test]
fn steady_pushes_allocate_nothing() {
let mut profiler = Profiler::new();
let start = Instant::now();
let records = frame_records(start);
profiler.push(timing(start), &records);
let pool = profiler.records.as_ptr();
for _ in 0..PROFILER_FRAMES * 3 {
profiler.push(timing(start), &records);
}
assert_eq!(profiler.records.as_ptr(), pool);
assert_eq!(profiler.records.len(), PROFILER_RECORDS);
assert!(profiler.slots.capacity() >= PROFILER_FRAMES);
assert_eq!(profiler.len(), PROFILER_FRAMES);
}
#[test]
fn a_frame_held_takes_its_gpu_time_and_one_not_held_does_not() {
let mut profiler = Profiler::new();
let start = Instant::now();
let gpu = GpuTiming::new(start + MS, 140 * US, 290 * US);
assert_eq!(gpu.total(), 430 * US);
assert_eq!(profiler.next_index(), 0);
assert!(!profiler.set_gpu(0, gpu));
for _ in 0..3 {
profiler.push(timing(start), &frame_records(start));
}
assert_eq!(profiler.next_index(), 3);
assert!(profiler.set_gpu(1, gpu));
let held: Vec<Option<GpuTiming>> = profiler.frames().map(|frame| frame.gpu).collect();
assert_eq!(held, [None, Some(gpu), None]);
profiler.set_paused(true);
profiler.push(timing(start), &frame_records(start));
assert_eq!(profiler.next_index(), 4);
assert!(!profiler.set_gpu(3, gpu));
profiler.set_paused(false);
for _ in 0..PROFILER_FRAMES {
profiler.push(timing(start), &frame_records(start));
}
assert!(!profiler.set_gpu(1, gpu));
assert!(profiler.frames().all(|frame| frame.gpu.is_none()));
let later = GpuTiming::new(start, MS, MS);
assert!(profiler.set_gpu(100, gpu));
assert!(profiler.set_gpu(100, later));
assert_eq!(profiler.frame(100).and_then(|frame| frame.gpu), Some(later));
}
#[derive(Debug)]
struct Event {
tid: i64,
name: String,
start: i64,
end: i64,
}
fn events(text: &str) -> (Value, Vec<Event>) {
let value = json::parse(text, Limits::default()).expect("the trace parses");
let list = value
.get("traceEvents")
.and_then(Value::as_array)
.expect("traceEvents is an array")
.to_vec();
let mut complete = Vec::new();
for event in &list {
let field = |key: &str| event.get(key).expect(key);
assert_eq!(field("pid").as_i64(), Some(PID));
let tid = field("tid").as_i64().expect("a track");
assert!(tid == TID || tid == GPU_TID, "{event:?}");
if field("ph").as_str() == Some("X") {
let start = field("ts").as_i64().expect("ts is a whole number");
let dur = field("dur").as_i64().expect("dur is a whole number");
complete.push(Event {
tid,
name: field("name").as_str().expect("a name").to_string(),
start,
end: start + dur,
});
}
}
(Value::Array(list), complete)
}
fn depths(events: &[Event]) -> Vec<(String, usize)> {
let mut sorted: Vec<&Event> = events.iter().collect();
sorted.sort_by(|a, b| a.start.cmp(&b.start).then(b.end.cmp(&a.end)));
let mut open: Vec<&Event> = Vec::new();
let mut depths = Vec::new();
for event in sorted {
while open.last().is_some_and(|parent| parent.end <= event.start) {
open.pop();
}
if let Some(parent) = open.last() {
assert!(
event.end <= parent.end,
"{event:?} crosses the end of {parent:?}"
);
}
depths.push((event.name.clone(), open.len()));
open.push(event);
}
depths
}
#[test]
fn the_trace_parses_with_every_frame_and_scope_nested() {
let mut profiler = Profiler::new();
let base = Instant::now();
for index in 0..3 {
let start = base + index * 16 * MS;
profiler.push(timing(start), &frame_records(start));
}
let (all, complete) = events(&profiler.trace_json());
let Value::Array(all) = all else {
unreachable!()
};
assert_eq!(all.len(), 1 + 3 + 3 * 4);
assert_eq!(all[0].get("ph").and_then(Value::as_str), Some("M"));
assert_eq!(
all[0]
.get("args")
.and_then(|args| args.get("name"))
.and_then(Value::as_str),
Some("main")
);
assert_eq!(complete.len(), 3 + 3 * 4);
assert!(complete.iter().all(|event| event.tid == TID));
let first = &complete[..5];
let names: Vec<&str> = first.iter().map(|event| event.name.as_str()).collect();
assert_eq!(
names,
[
"frame",
"nadir::tick",
"player_move",
"movement",
"nadir::render"
]
);
assert_eq!((first[0].start, first[0].end), (0, 16_000));
assert_eq!((first[1].start, first[1].end), (5, 505));
assert_eq!((first[2].start, first[2].end), (10, 110));
assert_eq!(complete[5].start, 16_000);
assert_eq!(
all[1]
.get("args")
.and_then(|args| args.get("index"))
.and_then(Value::as_i64),
Some(0)
);
let depths = depths(&complete);
let expected = [
("frame", 0),
("nadir::tick", 1),
("player_move", 2),
("movement", 2),
("nadir::render", 1),
];
for (index, chunk) in depths.chunks(5).enumerate() {
let chunk: Vec<(&str, usize)> = chunk
.iter()
.map(|(name, depth)| (name.as_str(), *depth))
.collect();
assert_eq!(chunk, expected, "frame {index}");
}
}
#[test]
fn the_gpu_track_places_each_frame_s_passes_after_its_submission_and_the_frame_before() {
let mut profiler = Profiler::new();
let base = Instant::now();
for index in 0..4 {
let start = base + index * 16 * MS;
profiler.push(timing(start), &frame_records(start));
}
let at = |frame: u32, micros: u32| base + frame * 16 * MS + micros * US;
profiler.set_gpu(0, GpuTiming::new(at(0, 600), 300 * US, 700 * US));
profiler.set_gpu(2, GpuTiming::new(at(2, 600), 15 * MS, 5 * MS));
profiler.set_gpu(3, GpuTiming::new(at(3, 600), 100 * US, 200 * US));
let (all, complete) = events(&profiler.trace_json());
let Value::Array(all) = all else {
unreachable!()
};
let arg =
|event: &Value, key: &str| event.get("args").and_then(|args| args.get(key)).cloned();
let names: Vec<(Option<i64>, Option<Value>)> = all
.iter()
.filter(|event| event.get("ph").and_then(Value::as_str) == Some("M"))
.map(|event| (event.get("tid").and_then(Value::as_i64), arg(event, "name")))
.collect();
let name = |text: &str| Some(Value::String(text.to_string()));
assert_eq!(
names,
[(Some(TID), name("main")), (Some(GPU_TID), name("gpu"))]
);
let gpu: Vec<(&str, i64, i64)> = complete
.iter()
.filter(|event| event.tid == GPU_TID)
.map(|event| (event.name.as_str(), event.start, event.end))
.collect();
assert_eq!(
gpu,
[
("frame", 600, 1_600),
("world", 600, 900),
("output", 900, 1_600),
("frame", 32_600, 52_600),
("world", 32_600, 47_600),
("output", 47_600, 52_600),
("frame", 52_600, 52_900),
("world", 52_600, 52_700),
("output", 52_700, 52_900),
]
);
let frames: Vec<(Option<i64>, Option<f64>)> = all
.iter()
.filter(|event| {
event.get("tid").and_then(Value::as_i64) == Some(GPU_TID)
&& event.get("name").and_then(Value::as_str) == Some("frame")
})
.map(|event| {
let index = arg(event, "index").and_then(|value| value.as_i64());
(index, arg(event, "gpu_ms").and_then(|value| value.as_f64()))
})
.collect();
assert_eq!(
frames,
[
(Some(0), Some(1.0)),
(Some(2), Some(20.0)),
(Some(3), Some(0.3))
]
);
let (cpu, gpu): (Vec<Event>, Vec<Event>) =
complete.into_iter().partition(|event| event.tid == TID);
assert_eq!(cpu.len(), 4 + 4 * 4);
depths(&cpu);
let nested: Vec<(String, usize)> = depths(&gpu);
let expected = [("frame", 0), ("world", 1), ("output", 1)].repeat(3);
let nested: Vec<(&str, usize)> = nested
.iter()
.map(|(name, depth)| (name.as_str(), *depth))
.collect();
assert_eq!(nested, expected);
}
#[test]
fn times_between_microseconds_keep_scopes_nested_and_frames_meeting() {
const NS: Duration = Duration::from_nanos(1);
let length = 16_666_667 * NS;
let mut profiler = Profiler::new();
let base = Instant::now();
for index in 0..4 {
let start = base + index * length;
let records = [
record("child", start + 900 * NS, 300 * NS, 1),
record("parent", start + 400 * NS, 1_200 * NS, 0),
];
profiler.push(FrameTiming::new(start, length, MS), &records);
}
let (_, complete) = events(&profiler.trace_json());
let frames: Vec<(i64, i64)> = complete
.iter()
.filter(|event| event.name == "frame")
.map(|event| (event.start, event.end))
.collect();
assert_eq!(
frames,
[
(0, 16_666),
(16_666, 33_333),
(33_333, 50_000),
(50_000, 66_666)
]
);
depths(&complete);
for (index, chunk) in complete.chunks(3).enumerate() {
let [frame, parent, child] = chunk else {
panic!("three events a frame");
};
assert_eq!(
(
frame.name.as_str(),
parent.name.as_str(),
child.name.as_str()
),
("frame", "parent", "child")
);
for (outer, inner) in [(frame, parent), (parent, child)] {
assert!(
outer.start <= inner.start && inner.end <= outer.end,
"frame {index}: {inner:?} is not inside {outer:?}"
);
}
}
assert_eq!((complete[7].start, complete[7].end), (33_333, 33_334));
assert_eq!((complete[8].start, complete[8].end), (33_334, 33_334));
}
#[test]
fn an_empty_profiler_writes_a_trace_of_the_thread_name_alone() {
let (all, complete) = events(&Profiler::new().trace_json());
assert_eq!(all.as_array().map(<[Value]>::len), Some(1));
assert!(complete.is_empty());
}
#[test]
fn names_are_escaped_and_a_scope_before_the_first_frame_starts_at_0() {
let mut profiler = Profiler::new();
let base = Instant::now() + MS;
let records = [record("say \"hi\"\n", base - MS, 2 * MS, 0)];
profiler.push(timing(base), &records);
let (_, complete) = events(&profiler.trace_json());
assert_eq!(complete[1].name, "say \"hi\"\n");
assert_eq!((complete[1].start, complete[1].end), (0, 1000));
}
}