diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index c96801fc..a0c3d6f9 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -22459,12 +22459,16 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( if waving { wave_submit(fctx, wave_job.0, wave_job.1); } + // lane-timeline: this tile's last symbol is read here; its wavefront + // workers are drained by `_wave`'s drop at the end of the iteration. + crate::timeline::tile_done(); flush_recon(fctx, &mut y, &mut u, &mut v); if tile_num == tile_info.context_update_tile_id { result_cdfs = cdfs; } } + crate::timeline::recon_done(); // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against @@ -22596,6 +22600,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( scratch_return(db_u.data.into_owned()); scratch_return(db_y.data.into_owned()); } + crate::timeline::filters_done(); let (fw, fh) = (lr_w, frame_height as usize); // An upscaled frame is already at its final size with no mi-aligned @@ -34751,12 +34756,16 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( if waving { wave_submit(fctx, wave_job.0, wave_job.1); } + // lane-timeline: this tile's last symbol is read here; its wavefront + // workers are drained by `_wave`'s drop at the end of the iteration. + crate::timeline::tile_done(); flush_recon(fctx, &mut y, &mut u, &mut v); if tile_num == tile_info.context_update_tile_id { result_cdfs = cdfs; } } + crate::timeline::recon_done(); // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against @@ -34790,6 +34799,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // out; from here the picture is deblocked and CDEF-filtered exactly as // the whole-frame path leaves it. let pipelined = pipe.is_some(); + crate::timeline::note_pipe(pipelined); if let Some(p) = &mut pipe { p.finish(); } @@ -34901,6 +34911,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( scratch_return(db_y.data.into_owned()); } + crate::timeline::filters_done(); let motion_field = build_motion_field( &grid, mi_cols as usize, diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index e7d61ba3..dd412d3e 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -48,6 +48,7 @@ mod restoration; pub mod sequence; mod superres; pub mod stream; +mod timeline; pub mod tile; pub mod transform; mod warp; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index d55cad0a..b4a0bfab 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -317,6 +317,7 @@ impl Reorder { while let Some((picture, decode_idx, shown)) = self.pending.remove(&self.next) { self.next += 1; sink(&picture, decode_idx, shown)?; + crate::timeline::output(decode_idx); } Ok(()) } @@ -552,6 +553,10 @@ pub fn decode_stream_with_threads( // keeps every counter-reading gate meaningful). let mut slot_promises: [Option>; NUM_REF_FRAMES] = std::array::from_fn(|_| None); + // lane-timeline: which decoded frame installed each slot's promise, so + // the timeline records a dependency EDGE (frame -> producing frame) and + // not just a slot number. `usize::MAX` = nobody yet. + let mut slot_owner = [usize::MAX; NUM_REF_FRAMES]; let mut pos = 0usize; // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec @@ -612,8 +617,11 @@ pub fn decode_stream_with_threads( for i in 0..NUM_REF_FRAMES { if header.refresh_frame_flags & (1 << i) != 0 { slot_promises[i] = Some(promise.clone()); + slot_owner[i] = slot_owner[slot]; } } + let cap_t0 = crate::timeline::now(); + let capped = in_flight_shows >= in_flight_cap; while in_flight_shows >= in_flight_cap { collect_one( &rx, @@ -623,6 +631,9 @@ pub fn decode_stream_with_threads( &mut sink, )?; } + if capped { + crate::timeline::cap_wait("show", cap_t0, crate::timeline::now()); + } let (job_seq, decode_idx) = (emit_seq, pictures_decoded); emit_seq += 1; pictures_shown += 1; @@ -813,6 +824,8 @@ pub fn decode_stream_with_threads( // deadlock argument). A key frame stays inline: it resets the whole // bank and reads nothing, so there is nothing to gain. if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame { + let cap_t0 = crate::timeline::now(); + let capped = in_flight_decodes >= in_flight_cap; while in_flight_decodes >= in_flight_cap { collect_one( &rx, @@ -822,6 +835,9 @@ pub fn decode_stream_with_threads( &mut sink, )?; } + if capped { + crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now()); + } // Exactly the slots this frame reads: `ref_frame_idx` names its // references, and its `primary_ref_frame` CDFs/segment map, its // reference order hints and every field `setup_motion_field` @@ -833,11 +849,13 @@ pub fn decode_stream_with_threads( let slot = header.ref_frame_idx[i] as usize; deps[slot] = slot_promises[slot].clone(); } + let dep_owner = slot_owner; let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending); if let Some(promise) = &produces { for i in 0..NUM_REF_FRAMES { if header.refresh_frame_flags & (1 << i) != 0 { slot_promises[i] = Some(promise.clone()); + slot_owner[i] = pictures_decoded; } } } @@ -850,18 +868,28 @@ pub fn decode_stream_with_threads( } let tx = tx.clone(); let dump = final_dump.clone(); + crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown); jobs.submit(move || { let promise = produces; let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + crate::timeline::start(decode_idx); // The wait happens HERE, off the parsing thread, and only // for this frame's own references. let mut resolved: [Option>; NUM_REF_FRAMES] = std::array::from_fn(|_| None); for (slot, dep) in deps.iter().enumerate() { if let Some(dep) = dep { + let t0 = crate::timeline::now(); resolved[slot] = Some(dep.wait()?); + crate::timeline::ref_wait( + decode_idx, + slot, + dep_owner[slot], + crate::timeline::now().saturating_sub(t0), + ); } } + crate::timeline::refs_ready(); // Fresh per-thread state: every field this path reads is // written from this frame's own header before it is read. let fctx = crate::decode::FrameCtx::new(); @@ -903,6 +931,7 @@ pub fn decode_stream_with_threads( seg_map: out.seg_map, order_hint: header.order_hint, })); + crate::timeline::slot_fulfil(); } // Grain is synthesised for OUTPUT only: a hidden frame is // reported to the sink clean, exactly as the inline path @@ -918,6 +947,7 @@ pub fn decode_stream_with_threads( } else { picture }; + crate::timeline::grain_done(); Ok((output, decode_idx, shown)) })) .unwrap_or_else(|_| { @@ -993,6 +1023,7 @@ pub fn decode_stream_with_threads( for i in 0..NUM_REF_FRAMES { if header.refresh_frame_flags & (1 << i) != 0 { slot_promises[i] = Some(promise.clone()); + slot_owner[i] = pictures_decoded - 1; } } } @@ -1055,6 +1086,7 @@ pub fn decode_stream_with_threads( )?; } debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); + crate::timeline::dump(); Ok(()) } @@ -1482,6 +1514,18 @@ fn decode_frame( // reads temporal candidates. let ref_order_hints = snap.ref_order_hints; + crate::timeline::bind( + decode_idx, + if header.frame_type == FrameType::Key { + 'K' + } else if header.show_frame { + 'P' + } else { + 'A' + }, + header.show_frame, + ); + crate::timeline::hdr_done(); let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key { let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs( &tile_bufs, diff --git a/crates/ec-av1/src/timeline.rs b/crates/ec-av1/src/timeline.rs new file mode 100644 index 00000000..1591e2bd --- /dev/null +++ b/crates/ec-av1/src/timeline.rs @@ -0,0 +1,262 @@ +//! lane-timeline: `EC_AV1_TIMELINE=1` frame-granularity decode timeline. +//! +//! The threaded decoder (`stream.rs`) is bounded by *something* -- reference +//! latency, the dispatcher's in-flight cap, the filter tail or the output +//! path -- and no instrument could tell which: `EC_AV1_WAVE_STATS` counts +//! superblocks, `perf` counts instructions, neither sees the dependency +//! graph. This records ~10 timestamps per coded frame (submit, worker start, +//! reference waits, parse, recon, filters, slot publish, grain, output) on +//! one monotonic clock and dumps them as TSV at stream end; +//! `scripts/av1-timeline-report.py` reads that and walks the critical path. +//! +//! Cost when off: one relaxed atomic load ([`env_flag!`]'s `LazyLock`) +//! per event, at frame granularity -- ~10 loads per frame, nothing per block. + +use std::sync::Mutex; +use std::time::Instant; + +/// Process start, the zero of every timestamp below. +static START: std::sync::LazyLock = std::sync::LazyLock::new(Instant::now); + +/// `EC_AV1_TIMELINE` -- one atomic load per call site after the first. +pub(crate) fn on() -> bool { + crate::envflags::env_flag!("EC_AV1_TIMELINE") +} + +fn now_us() -> u64 { + START.elapsed().as_micros() as u64 +} + +/// One coded frame's timestamps, in microseconds since [`START`]; 0 = never +/// reached (a key frame decodes inline, so it has no submit/start/publish). +#[derive(Clone, Default)] +struct Rec { + used: bool, + ftype: char, + show: bool, + submit: u64, + start: u64, + refs_ready: u64, + hdr_done: u64, + tile_done: u64, + recon_done: u64, + filters_done: u64, + slot_fulfil: u64, + grain_done: u64, + output: u64, + /// Slot this frame blocked on longest, which frame produced it, and + /// for how long. + wait_slot: i32, + wait_owner: i64, + wait_us: u64, + /// The producing frame of every slot it waited on, for the DAG. + deps: Vec, + pipe: bool, +} + +#[derive(Default)] +struct Log { + frames: Vec, + /// Dispatcher blocks at the in-flight bound: (kind, begin, end). + caps: Vec<(&'static str, u64, u64)>, +} + +static LOG: Mutex> = Mutex::new(None); + +fn with(f: F) { + let mut g = LOG.lock().expect("timeline"); + f(g.get_or_insert_with(Log::default)); +} + +fn rec(idx: usize, f: F) { + with(|log| { + if log.frames.len() <= idx { + log.frames.resize(idx + 1, Rec { wait_slot: -1, wait_owner: -1, ..Rec::default() }); + } + let r = &mut log.frames[idx]; + r.used = true; + f(r); + }); +} + +// The frame this thread is decoding, so `decode.rs`'s phase marks need no +// new parameter threaded through the tile decoders. +thread_local! { + static CUR: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }; +} + +/// Dispatch (parsing thread), before the job is queued. +#[cold] +pub(crate) fn submit(idx: usize, ftype: char, show: bool) { + if !on() { + return; + } + let t = now_us(); + rec(idx, |r| { + r.ftype = ftype; + r.show = show; + r.submit = t; + }); +} + +/// A worker picked the job up. Also binds this thread to `idx`. +#[cold] +pub(crate) fn start(idx: usize) { + if !on() { + return; + } + CUR.with(|c| c.set(idx)); + let t = now_us(); + rec(idx, |r| r.start = t); +} + +/// Binds a thread to `idx` without a start timestamp (the inline key-frame +/// path, which is dispatched by nobody). +#[cold] +pub(crate) fn bind(idx: usize, ftype: char, show: bool) { + if !on() { + return; + } + CUR.with(|c| c.set(idx)); + rec(idx, |r| { + r.ftype = ftype; + r.show = show; + }); +} + +/// One resolved `SlotPromise::wait`, with the slot and how long it blocked. +#[cold] +pub(crate) fn ref_wait(idx: usize, slot: usize, owner: usize, waited_us: u64) { + if !on() { + return; + } + rec(idx, |r| { + if owner != usize::MAX && !r.deps.contains(&owner) { + r.deps.push(owner); + } + if waited_us > r.wait_us { + r.wait_us = waited_us; + r.wait_slot = slot as i32; + r.wait_owner = if owner == usize::MAX { -1 } else { owner as i64 }; + } + }); +} + +macro_rules! stamp { + ($name:ident, $field:ident) => { + #[doc = concat!("Marks `", stringify!($field), "` for the frame this thread is decoding.")] + #[cold] + pub(crate) fn $name() { + if !on() { + return; + } + let (idx, t) = (CUR.with(std::cell::Cell::get), now_us()); + if idx != usize::MAX { + rec(idx, |r| r.$field = t); + } + } + }; +} +stamp!(refs_ready, refs_ready); +stamp!(hdr_done, hdr_done); +stamp!(tile_done, tile_done); +stamp!(recon_done, recon_done); +stamp!(filters_done, filters_done); +stamp!(slot_fulfil, slot_fulfil); +stamp!(grain_done, grain_done); + +/// Whether this frame's filters ran pipelined per superblock row. +#[cold] +pub(crate) fn note_pipe(pipe: bool) { + if !on() { + return; + } + let idx = CUR.with(std::cell::Cell::get); + if idx != usize::MAX { + rec(idx, |r| r.pipe = pipe); + } +} + +/// The picture reached the sink. Only a frame that finished on a worker +/// (`grain_done`) and has not been emitted yet takes the stamp -- a +/// `show_existing_frame` re-output reports a decode index that is not its +/// own, and must not overwrite another frame's row. +#[cold] +pub(crate) fn output(idx: usize) { + if !on() { + return; + } + let t = now_us(); + with(|log| { + if let Some(r) = log.frames.get_mut(idx) + && r.output == 0 + // A frame that finished on a worker, or the inline key frame + // (never submitted) that has passed its filters. + && (r.grain_done != 0 || (r.submit == 0 && r.filters_done != 0)) + { + r.output = t; + } + }); +} + +/// The parsing thread blocked at the in-flight bound. +#[cold] +pub(crate) fn cap_wait(kind: &'static str, begin: u64, end: u64) { + if !on() { + return; + } + with(|log| log.caps.push((kind, begin, end))); +} + +/// `now_us` for the two call sites that need a begin timestamp of their own. +pub(crate) fn now() -> u64 { + if !on() { + return 0; + } + now_us() +} + +/// Writes every row to stderr as TSV and clears the log. +#[cold] +pub(crate) fn dump() { + if !on() { + return; + } + let taken = LOG.lock().expect("timeline").take(); + let Some(log) = taken else { return }; + let mut out = String::new(); + out.push_str( + "TL_HDR\tidx\ttype\tshow\tsubmit\tstart\trefs_ready\thdr_done\ttile_done\trecon_done\tfilters_done\tslot_fulfil\tgrain_done\toutput\twait_slot\twait_owner\twait_us\tpipe\tdeps\n", + ); + for (idx, r) in log.frames.iter().enumerate() { + if !r.used { + continue; + } + let deps: Vec = r.deps.iter().map(std::string::ToString::to_string).collect(); + out.push_str(&format!( + "TL\t{idx}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", + r.ftype, + u8::from(r.show), + r.submit, + r.start, + r.refs_ready, + r.hdr_done, + r.tile_done, + r.recon_done, + r.filters_done, + r.slot_fulfil, + r.grain_done, + r.output, + r.wait_slot, + r.wait_owner, + r.wait_us, + u8::from(r.pipe), + if deps.is_empty() { "-".to_string() } else { deps.join(",") }, + )); + } + for (kind, b, e) in &log.caps { + out.push_str(&format!("TL_CAP\t{kind}\t{b}\t{e}\n")); + } + out.push_str(&format!("TL_END\t{}\n", now_us())); + eprint!("{out}"); +} diff --git a/scripts/av1-timeline-report.py b/scripts/av1-timeline-report.py new file mode 100755 index 00000000..c9a9f46e --- /dev/null +++ b/scripts/av1-timeline-report.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +"""Reads `EC_AV1_TIMELINE=1` TSV (stderr of decode_probe) and reports what +bounds the wall: per-phase durations, reference waits, the critical path +through the reference DAG, concurrency over time, and dispatcher cap waits. + +Usage: EC_AV1_TIMELINE=1 decode_probe f.obu 2>tl.tsv; av1-timeline-report.py tl.tsv +""" +import sys +from statistics import median + +COLS = ("idx type show submit start refs_ready hdr_done tile_done recon_done " + "filters_done slot_fulfil grain_done output wait_slot wait_owner wait_us " + "pipe deps").split() +INT = set(COLS) - {"type", "deps"} + +# (label, from, to) -- the phases of one frame, in order. +PHASES = [ + ("queue submit->start", "submit", "start"), + ("refwait start->refs", "start", "refs_ready"), + ("setup refs->hdr", "refs_ready", "hdr_done"), + ("parse hdr->tile", "hdr_done", "tile_done"), + ("recontail tile->recon", "tile_done", "recon_done"), + ("filters recon->filt", "recon_done", "filters_done"), + ("publish filt->fulfil", "filters_done", "slot_fulfil"), + ("grain fulfil->grain", "slot_fulfil", "grain_done"), + ("outwait grain->output", "grain_done", "output"), +] +# Which phase a chain segment's time is charged to (same order). +CHAIN_KEYS = [p[0].split()[0] for p in PHASES] + + +def load(path): + frames, caps, end = [], [], 0 + with (open(path) if path != "-" else sys.stdin) as fh: + for line in fh: + f = line.rstrip("\n").split("\t") + if f[0] == "TL": + r = dict(zip(COLS, f[1:])) + for k in INT: + r[k] = int(r[k]) + r["deps"] = [] if r["deps"] == "-" else [int(x) for x in r["deps"].split(",")] + frames.append(r) + elif f[0] == "TL_CAP": + caps.append((f[1], int(f[2]), int(f[3]))) + elif f[0] == "TL_END": + end = int(f[1]) + return {f["idx"]: f for f in frames}, caps, end + + +def ms(us): + return us / 1000.0 + + +def stats(vals): + vals = sorted(v for v in vals if v is not None) + if not vals: + return None + p90 = vals[min(len(vals) - 1, int(round(0.9 * (len(vals) - 1))))] + return median(vals), p90, vals[-1], sum(vals), len(vals) + + +def dur(r, a, b): + """Duration of one phase, or None when either end was never reached.""" + if r[a] == 0 or r[b] == 0 or r[b] < r[a]: + return None + return r[b] - r[a] + + +def main(): + path = sys.argv[1] if len(sys.argv) > 1 else "-" + fr, caps, end = load(path) + if not fr: + sys.exit("no TL rows") + t0 = min(min(v for k, v in r.items() if k in INT and k not in + ("idx", "show", "wait_slot", "wait_owner", "wait_us", "pipe") and v > 0) + for r in fr.values()) + wall = end - t0 + n = len(fr) + npipe = sum(r["pipe"] for r in fr.values()) + print(f"frames={n} (key={sum(1 for r in fr.values() if r['type']=='K')} " + f"shown={sum(r['show'] for r in fr.values())} pipelined_filters={npipe}/{n}) " + f"wall={ms(wall):.1f} ms (first event {ms(t0):.1f} ms, end {ms(end):.1f} ms)") + + print("\n(a) per-frame phase durations, ms") + print(f"{'phase':24} {'n':>4} {'median':>8} {'p90':>8} {'max':>8} {'sum':>9} {'sum/wall':>8}") + for label, a, b in PHASES: + s = stats([dur(r, a, b) for r in fr.values()]) + if not s: + print(f"{label:24} -") + continue + med, p90, mx, tot, cnt = s + print(f"{label:24} {cnt:>4} {ms(med):>8.2f} {ms(p90):>8.2f} {ms(mx):>8.2f} " + f"{ms(tot):>9.1f} {tot/wall:>8.2f}") + s = stats([dur(r, "start", "grain_done") for r in fr.values()]) + if s: + print(f"{'TOTAL start->grain':24} {s[4]:>4} {ms(s[0]):>8.2f} {ms(s[1]):>8.2f} " + f"{ms(s[2]):>8.2f} {ms(s[3]):>9.1f} {s[3]/wall:>8.2f}") + + print("\n(b) reference wait (start -> refs_ready), ms") + waits = [(dur(r, "start", "refs_ready") or 0, r) for r in fr.values() if r["start"]] + s = stats([w for w, _ in waits]) + print(f" n={s[4]} median={ms(s[0]):.2f} p90={ms(s[1]):.2f} max={ms(s[2]):.2f} " + f"sum={ms(s[3]):.1f} ({s[3]/wall:.2f}x wall)") + zero = sum(1 for w, _ in waits if w < 1000) + print(f" frames waiting <1 ms: {zero}/{len(waits)}") + print(" top waiters (frame -> longest-blocking producer):") + for w, r in sorted(waits, key=lambda x: -x[0])[:10]: + print(f" f{r['idx']:<4}{r['type']} waited {ms(w):8.2f} on slot {r['wait_slot']} " + f"produced by f{r['wait_owner']} (deps {r['deps']})") + + # (c) critical path. A frame's critical predecessor is the dependency + # whose slot publish is the LAST one -- the edge that actually released + # this frame's refs_ready. + def pred(r): + best, bt = None, -1 + for d in r["deps"]: + p = fr.get(d) + if p is None: + continue + t = own_w[d] + if t > bt: + best, bt = p, t + return best + + # Walk back from the frame on the longest WORK-WEIGHTED chain (the frame + # that finishes last is often in a short last-GOP chain: a key frame + # resets the DAG, so wall-clock-last is not dependency-deepest). + own_w = {} + for i in sorted(fr): + r = fr[i] + own_w[i] = max([own_w.get(d, 0) for d in r["deps"]] + [0]) + sum( + dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7]) + tail = fr[max(own_w, key=lambda k: own_w[k])] + chain, cur = [], tail + while cur is not None: + chain.append(cur) + cur = pred(cur) + chain.reverse() + head = chain[0] + span_a = head["hdr_done"] or head["start"] or t0 + span_b = max(tail["output"], tail["grain_done"]) + print(f"\n(c) critical path: {len(chain)} frames " + f"({chain[0]['idx']} -> {chain[-1]['idx']}), " + f"{ms(span_b - span_a):.1f} ms = {(span_b-span_a)/wall*100:.1f}% of wall") + charge = dict.fromkeys(CHAIN_KEYS, 0) + slack = 0 + for i, r in enumerate(chain): + for (label, a, b) in PHASES: + d = dur(r, a, b) + if d is None: + continue + k = label.split()[0] + if i == 0 and k in ("queue", "refwait"): + continue + # A frame's own wait is charged only for the part after its + # predecessor published -- before that the predecessor's own + # phases already account for the time. + if k == "refwait": + p = chain[i - 1] + d = max(0, r["refs_ready"] - max(r["start"], p["slot_fulfil"] or p["filters_done"])) + if k == "outwait" and r is not tail: + continue + charge[k] += d + if i: + p = chain[i - 1] + pt = p["slot_fulfil"] or p["filters_done"] + if r["start"] and r["start"] > pt: + slack += r["start"] - pt + print(f" {'segment':12} {'ms':>9} {'% of chain':>11}") + tot = span_b - span_a + for k in CHAIN_KEYS: + if charge[k]: + print(f" {k:12} {ms(charge[k]):>9.1f} {charge[k]/tot*100:>10.1f}%") + print(f" {'(late start)':12} {ms(slack):>9.1f} {slack/tot*100:>10.1f}% " + "producer published before the consumer's worker even started") + print(f" chain frames: {[r['idx'] for r in chain][:40]}" + f"{' ...' if len(chain) > 40 else ''}") + + # Infinite-core lower bound: earliest finish of every frame if a core + # were always free -- own work only, no queueing. + own = {} + for i in sorted(fr): + r = fr[i] + w = sum(dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7]) + own[i] = max([own.get(d, 0) for d in r["deps"]] + [0]) + w + crit = max(own, key=lambda k: own[k]) + print(f" infinite-core bound (longest work-weighted chain, ends at f{crit}): " + f"{ms(own[crit]):.1f} ms = {own[crit]/wall*100:.1f}% of wall") + work = sum(sum(dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7]) for r in fr.values()) + print(f" frame-thread work total {ms(work):.1f} ms = {work/wall:.2f} cores' worth; " + f"work/bound = {work/own[crit]:.2f} (the parallelism the DAG would need)") + + print("\n(d) concurrency (frames between start and slot publish), 10 ms ticks") + def tick(live, label): + counts = [] + t = t0 + while t < end: + counts.append(sum(1 for a, b in live if a <= t < b)) + t += 10000 + counts.sort() + lt2 = sum(1 for c in counts if c < 2) + print(f" {label:9} median={counts[len(counts)//2]:3} " + f"p90={counts[int(0.9*(len(counts)-1))]:3} max={counts[-1]:3} " + f"mean={sum(counts)/len(counts):5.2f} <2 for {lt2/len(counts)*100:5.1f}% of wall" + f" (<1: {sum(1 for c in counts if c<1)/len(counts)*100:.1f}%)") + + end_of = lambda r: r["slot_fulfil"] or r["grain_done"] or r["filters_done"] + # in flight = dispatched and not yet published (includes frames blocked on + # a reference); running = past its reference waits, i.e. actually runnable. + tick([(r["start"], end_of(r)) for r in fr.values() if r["start"]], "in-flight") + tick([(r["refs_ready"], end_of(r)) for r in fr.values() if r["refs_ready"]], "running") + tick([(r["hdr_done"], r["tile_done"]) for r in fr.values() if r["hdr_done"] and r["tile_done"]], + "parsing") + + print("\n(e) dispatcher in-flight cap waits") + for kind in ("decode", "show"): + k = [(b, e) for t_, b, e in caps if t_ == kind] + tot = sum(e - b for b, e in k) + mx = max((e - b for b, e in k), default=0) + print(f" {kind:7} blocks={len(k):5} total={ms(tot):9.1f} ms " + f"({tot/wall*100:5.1f}% of wall) max={ms(mx):.2f} ms") + + +if __name__ == "__main__": + main()