diff --git a/crates/metal2vulkan-runtime/examples/queue_share.rs b/crates/metal2vulkan-runtime/examples/queue_share.rs index fbc2c35e4..09fa11e72 100644 --- a/crates/metal2vulkan-runtime/examples/queue_share.rs +++ b/crates/metal2vulkan-runtime/examples/queue_share.rs @@ -4,15 +4,15 @@ //! ```sh //! cargo run --release -p metal2vulkan-runtime --example queue_share -- \ //! [--policy adaptive|per-queue] [--seconds S] [--dispatches N] [--unshared] \ -//! [--threads T --in-flight F [--one-vk-queue]] +//! [--threads T --in-flight F [--one-vk-queue]] [--long-ms L] [--period-ms P] //! ``` //! //! Every command buffer is one of two kinds. A *draw*: a render pass over a 512x512 `RGBA8Unorm` //! texture, cleared and one triangle drawn (`colored_vertex` and `colored_fragment` of the //! repository's owned fixture `runtime_examples.metal`, assembled by `llvm-as` on `PATH`). A *long* //! one: `--dispatches` dispatches of `scale_and_offset` over one buffer, sized as the run starts -//! so the command buffer's GPU time is 30 ms. Latencies are a command buffer's `commit` to the -//! start of its completed handler, on the host's clock. +//! so the command buffer's GPU time is `--long-ms` (30 ms by default). Latencies are a command +//! buffer's `commit` to the start of its completed handler, on the host's clock. //! //! - **check**: the device's check of its GPU's idling between `VkQueue`s: its verdict and //! switch cost (run where no record of it is kept, read back where one is). @@ -22,6 +22,12 @@ //! compositor's queue with `new_command_queue_unshared`. //! - **pipelined**: as isolation, but the application keeps two long command buffers in flight, //! so its queue holds no idle point. +//! - **frames**: a compositor thread commits one draw every `--period-ms` (16 ms by default) and +//! never waits, beside an application thread that keeps `--in-flight` long command buffers in +//! flight (3 by default). The compositor's latencies and how many ran over 16 ms, the +//! application's long command buffers a second, and the device's counts of command buffers that +//! waited behind another queue's batch (`WorkCounts::command_buffers_behind_other_queues` and +//! kin). `--unshared` makes the compositor's queue with `new_command_queue_unshared`. //! - **trap**: as isolation, but the application alternates 500 ms of draws committed at 10,000 a //! second with 10 long command buffers. //! - **alternating**: as trap, with 2 ms of draws between each long command buffer; and @@ -52,9 +58,6 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; -/// A command buffer's GPU time a long one is sized for. -const LONG: Duration = Duration::from_millis(30); - /// A compositor's latency past which it counts as a stall. const STALL_MS: f64 = 10.0; @@ -78,6 +81,10 @@ struct Options { in_flight: usize, /// `rates` with every thread's queue on one `VkQueue`, each lent once so it never moves. one_vk_queue: bool, + /// A long command buffer's GPU time. + long: Duration, + /// `frames`: the compositor's period between commits. + period: Duration, } fn options() -> Options { @@ -91,6 +98,8 @@ fn options() -> Options { threads: 0, in_flight: 3, one_vk_queue: false, + long: Duration::from_millis(30), + period: Duration::from_millis(16), }; while let Some(arg) = args.next() { let mut value = || args.next().unwrap_or_else(|| panic!("{arg} needs a value")); @@ -108,6 +117,12 @@ fn options() -> Options { "--threads" => options.threads = value().parse().unwrap(), "--in-flight" => options.in_flight = value().parse().unwrap(), "--one-vk-queue" => options.one_vk_queue = true, + "--long-ms" => { + options.long = Duration::from_secs_f64(value().parse::().unwrap() / 1e3) + } + "--period-ms" => { + options.period = Duration::from_secs_f64(value().parse::().unwrap() / 1e3) + } other => panic!("unknown argument {other}"), } } @@ -127,6 +142,8 @@ struct Kit { /// The grid of one long command buffer's dispatches. grid: u64, dispatches: u64, + /// The GPU time a long command buffer is sized for. + long_time: Duration, } impl Kit { @@ -190,12 +207,13 @@ impl Kit { scale, grid: 1 << 20, dispatches: options.dispatches, + long_time: options.long, }; kit.size_long(); kit } - /// Size the long command buffers' grid so one's GPU time is [`LONG`]. + /// Size the long command buffers' grid so one's GPU time is `long_time`. fn size_long(&mut self) { let queue = self.device.new_command_queue().unwrap(); for _ in 0..3 { @@ -204,7 +222,7 @@ impl Kit { command_buffer.wait_until_completed().unwrap(); let gpu = command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap(); - let wanted = self.grid as f64 * LONG.as_secs_f64() / gpu.max(1e-6); + let wanted = self.grid as f64 * self.long_time.as_secs_f64() / gpu.max(1e-6); self.grid = (wanted as u64).clamp(1 << 16, MOST_FLOATS) & !63; } let command_buffer = self.long(&queue); @@ -396,20 +414,21 @@ fn compositor( /// The application's loop until `stop`, on its own thread: `long_every` long command buffers after /// each `short` of draws at 10,000 a second (none where `short` is zero), each long one waited for, -/// or with `in_flight` long ones in flight where above 1. +/// or with `in_flight` long ones in flight where above 1. Answers how many long ones completed. fn application( kit: &Arc, short: Duration, long_every: usize, in_flight: usize, stop: &Arc, -) -> std::thread::JoinHandle<()> { +) -> std::thread::JoinHandle { let kit = Arc::clone(kit); let stop = Arc::clone(stop); std::thread::spawn(move || { let queue = kit.device.new_command_queue().unwrap(); let target = kit.target(); let mut flying: std::collections::VecDeque = Default::default(); + let mut longs = 0u64; while !stop.load(Ordering::Relaxed) { if !short.is_zero() { let began = Instant::now(); @@ -434,12 +453,15 @@ fn application( flying.push_back(command_buffer); while flying.len() >= in_flight.max(1) { flying.pop_front().unwrap().wait_until_completed().unwrap(); + longs += 1; } } } for command_buffer in flying { command_buffer.wait_until_completed().unwrap(); + longs += 1; } + longs }) } @@ -472,6 +494,73 @@ fn beside(kit: &Arc, options: &Options, short: Duration, long_every: usize, ); } +/// A compositor committing one draw every `options.period` beside an application keeping +/// `options.in_flight` long command buffers in flight: the compositor's latencies, the +/// application's long command buffers a second, and the device's counts of waits behind other +/// queues' batches over the run. +fn frames(kit: &Arc, options: &Options) { + let stop = Arc::new(AtomicBool::new(false)); + let latencies = Arc::new(Mutex::new(Vec::new())); + let before = kit.device.work_counts(); + let began = Instant::now(); + let app = application(kit, Duration::ZERO, 1, options.in_flight, &stop); + std::thread::sleep(Duration::from_millis(50)); + let rate = 1.0 / options.period.as_secs_f64(); + let comp = compositor( + kit, + kit.queue(options.unshared), + rate, + &stop, + &latencies, + None, + ); + std::thread::sleep(Duration::from_secs_f64(options.seconds)); + stop.store(true, Ordering::Relaxed); + comp.join().unwrap(); + let longs = app.join().unwrap(); + let elapsed = began.elapsed().as_secs_f64(); + std::thread::sleep(Duration::from_millis(100)); + let c = kit.device.work_counts(); + let mut samples = latencies.lock().unwrap().clone(); + let over_16 = samples.iter().filter(|&&ms| ms > 16.0).count(); + let unshared_16 = c.unshared_command_buffers_behind_other_queues_over_16ms + - before.unshared_command_buffers_behind_other_queues_over_16ms; + let per_16 = |sum: u64| sum as f64 / unshared_16.max(1) as f64; + println!( + "frames (policy {:?}, compositor {} every {:?}, application {} in flight of {:.1} ms): compositor {}, {over_16} over 16 ms; application {:.2} long command buffers/s", + options.policy, + if options.unshared { "unshared" } else { "shared" }, + options.period, + options.in_flight, + kit.long_time.as_secs_f64() * 1e3, + summary(&mut samples), + longs as f64 / elapsed, + ); + println!( + " behind other queues: {} ({} over 16 ms, {} over 33 ms, longest {:.1} ms); unshared {} ({} over 16 ms, {} over 33 ms, longest {:.1} ms); unshared waits over 16 ms: {:.2} batches ahead on average, at most {}, longest run {:.1} ms on average, {} behind one run over 16 ms", + c.command_buffers_behind_other_queues - before.command_buffers_behind_other_queues, + c.command_buffers_behind_other_queues_over_16ms + - before.command_buffers_behind_other_queues_over_16ms, + c.command_buffers_behind_other_queues_over_33ms + - before.command_buffers_behind_other_queues_over_33ms, + c.wait_behind_other_queues_longest_nanos as f64 / 1e6, + c.unshared_command_buffers_behind_other_queues + - before.unshared_command_buffers_behind_other_queues, + unshared_16, + c.unshared_command_buffers_behind_other_queues_over_33ms + - before.unshared_command_buffers_behind_other_queues_over_33ms, + c.unshared_wait_behind_other_queues_longest_nanos as f64 / 1e6, + per_16(c.unshared_waits_over_16ms_batches_ahead - before.unshared_waits_over_16ms_batches_ahead), + c.unshared_waits_over_16ms_most_batches_ahead, + per_16( + c.unshared_waits_over_16ms_longest_runs_nanos + - before.unshared_waits_over_16ms_longest_runs_nanos + ) / 1e6, + c.unshared_waits_over_16ms_behind_one_long_run + - before.unshared_waits_over_16ms_behind_one_long_run, + ); +} + /// The GPU's idle time between command buffers of different queues, as a share of the span of /// `times` (queue, GPU start, GPU end), in GPU start order; with the switches counted. fn switch_idle(times: &mut [(usize, f64, f64)]) -> (f64, usize) { @@ -793,6 +882,7 @@ fn main() { "trap" => beside(&kit, &options, Duration::from_millis(500), 10, 1), "alternating" => beside(&kit, &options, Duration::from_millis(2), 1, 1), "slow-alternating" => beside(&kit, &options, Duration::from_millis(1500), 1, 1), + "frames" => frames(&kit, &options), "interleave" => interleave(&kit, &options), "rates" if options.threads > 0 => { rate(&kit, &options, options.threads, options.in_flight); diff --git a/crates/metal2vulkan-runtime/src/queue_wait.rs b/crates/metal2vulkan-runtime/src/queue_wait.rs index 3a7e2a9da..9cd377fda 100644 --- a/crates/metal2vulkan-runtime/src/queue_wait.rs +++ b/crates/metal2vulkan-runtime/src/queue_wait.rs @@ -27,6 +27,17 @@ //! whose value it reached from the front. No command queue of the device is looked at. Only //! command buffers' batches are seen: the runtime's own submissions (staging, checks, a step's //! run again) neither count nor are waited behind. +//! - **What it waited behind** (unshared queues' waits over 16 ms alone, +//! `WorkCounts::unshared_waits_over_16ms_batches_ahead` and kin): the batches in flight ahead of +//! it as its first batch took its value (the values past the one the host saw complete), and the +//! longest run among those it waited for: a run is the host's view of how long the oldest batch +//! in flight was so, from the completion seen before it (or its submission, where the host saw +//! every earlier batch complete) to the completion that ended it, so one batch's GPU work and +//! the host's lateness to see it end, or several batches seen complete at once. A wait one run +//! alone holds over 16 ms waits behind one long batch; one of many short runs, behind many +//! batches. The longest run of each wait being timed is kept as a sliding maximum over the runs +//! seen since the oldest one began: O(1) a completion, amortized, and no more runs kept than +//! the batches that wait was behind. use crate::device::lock; use crate::work_counts::Counters; @@ -47,9 +58,18 @@ struct Ahead { other: u64, /// The waits being timed, by the value each waits for, which rises. timed: VecDeque, + /// The host time its oldest batch in flight became so: the last completion it saw, or the + /// submission of a batch taken while the host saw every earlier one complete. + head_from: u64, + /// The runs seen while a wait is timed, numbered from 1, their nanoseconds falling from the + /// front: each the longest of those from it on (the module docs). + runs: VecDeque<(u64, u64)>, + /// The number of the last run kept. + run: u64, } /// A command buffer's wait behind another command queue's batch, being timed. +#[derive(Clone, Copy)] struct Timed { /// The value of the batch it waits for. through: u64, @@ -57,6 +77,21 @@ struct Timed { since: u64, /// Its command queue was made with `Device::new_command_queue_unshared`. unshared: bool, + /// The batches in flight ahead of it as it took its value. + ahead: u64, + /// The number of the last run kept before it began: the runs it waited for come after. + after_run: u64, +} + +/// A wait behind another command queue's batch that ended (`Counters::waited_behind_other_queue`). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Waited { + /// From its first batch's submission to the host's observation of the batch it waited for. + pub(crate) nanos: u64, + /// The batches in flight ahead of it as it took its value. + pub(crate) batches: u64, + /// The longest run among those it waited for (the module docs). + pub(crate) longest: u64, } /// A command buffer's first batch, as [`QueueWaits::taken`] times it. @@ -91,16 +126,25 @@ impl QueueWaits { } _ => ahead.other, }; + let before = ahead.last.map_or(0, |(last, _)| last); ahead.last = Some((value, queue)); + let completed = completed(); + // Taken while the host saw every earlier batch complete: its run begins here. + if completed >= before { + ahead.head_from = first.map_or_else(crate::gpu_time::host_nanos, |first| first.since); + } let Some(First { since, unshared }) = first else { return; }; - if through > completed() { + if through > completed { counts.behind_other_queue(unshared); + let after_run = ahead.run; ahead.timed.push_back(Timed { through, since, unshared, + ahead: value.saturating_sub(completed + 1), + after_run, }); } } @@ -109,14 +153,42 @@ impl QueueWaits { /// at or below it ends now. pub(crate) fn completed(&self, value: u64, counts: &Counters) { let mut ahead = lock(&self.0); - let mut at = None; + let now = crate::gpu_time::host_nanos(); + let length = now.saturating_sub(ahead.head_from); + ahead.head_from = now; + if !ahead.timed.is_empty() { + ahead.run += 1; + let run = ahead.run; + while ahead.runs.back().is_some_and(|&(_, nanos)| nanos <= length) { + ahead.runs.pop_back(); + } + ahead.runs.push_back((run, length)); + } while let Some(timed) = ahead.timed.front() { if timed.through > value { break; } - let now = *at.get_or_insert_with(crate::gpu_time::host_nanos); - counts.waited_behind_other_queue(now.saturating_sub(timed.since), timed.unshared); + let Timed { + since, + unshared, + ahead: batches, + after_run, + .. + } = *timed; + while ahead.runs.front().is_some_and(|&(run, _)| run <= after_run) { + ahead.runs.pop_front(); + } + let longest = ahead.runs.front().map_or(0, |&(_, nanos)| nanos); + let waited = Waited { + nanos: now.saturating_sub(since), + batches, + longest, + }; + counts.waited_behind_other_queue(waited, unshared); ahead.timed.pop_front(); } + if ahead.timed.is_empty() { + ahead.runs.clear(); + } } } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 9f3b97a00..1dca28cf4 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -245,6 +245,10 @@ pub(crate) struct Counters { /// Command buffers' waits behind other command queues' batches (`queue_wait.rs`): of every /// queue's, then of unshared queues' alone. behind_other_queues: [BehindOtherQueues; 2], + /// What unshared queues' waits over 16 ms waited behind (`queue_wait.rs`): the batches ahead + /// of each, summed and the most, its longest run, summed, and those whose longest run alone + /// was over 16 ms. + unshared_long_waits: [AtomicU64; 4], queue_switch_checks_run: AtomicU64, queue_switch_checks_recalled: AtomicU64, submit_checks_run: AtomicU64, @@ -2755,8 +2759,22 @@ impl Counters { } } - /// Such a command buffer's wait ended, `nanos` after its submission (`queue_wait.rs`). - pub(crate) fn waited_behind_other_queue(&self, nanos: u64, unshared: bool) { + /// Such a command buffer's wait ended, `waited.nanos` after its submission (`queue_wait.rs`). + pub(crate) fn waited_behind_other_queue( + &self, + waited: crate::queue_wait::Waited, + unshared: bool, + ) { + let nanos = waited.nanos; + if unshared && nanos > 16_000_000 { + let [batches, most, longest, one] = &self.unshared_long_waits; + batches.fetch_add(waited.batches, Ordering::Relaxed); + most.fetch_max(waited.batches, Ordering::Relaxed); + longest.fetch_add(waited.longest, Ordering::Relaxed); + if waited.longest > 16_000_000 { + one.fetch_add(1, Ordering::Relaxed); + } + } for tally in &self.behind_other_queues[..1 + usize::from(unshared)] { if nanos > 16_000_000 { tally.over_16ms.fetch_add(1, Ordering::Relaxed); @@ -5944,6 +5962,22 @@ pub struct WorkCounts { /// The longest wait of an unshared command queue's command buffer behind another command /// queue's batch, in nanoseconds, measured as `wait_behind_other_queues_longest_nanos`. pub unshared_wait_behind_other_queues_longest_nanos: u64, + /// Of the waits counted in `unshared_command_buffers_behind_other_queues_over_16ms`, the + /// batches in flight ahead of each on its `VkQueue` as its first batch went there (timeline + /// values submitted past the one the host saw complete), summed: divided by that count, how + /// many batches such a wait was behind. + pub unshared_waits_over_16ms_batches_ahead: u64, + /// The most batches in flight ahead of one of those waits, counted so. + pub unshared_waits_over_16ms_most_batches_ahead: u64, + /// The longest run each of those waits waited for, summed, in nanoseconds: a run is the + /// host's view of how long the oldest batch in flight on the `VkQueue` was so, from the + /// completion seen before it (or its submission onto a `VkQueue` the host saw idle) to the + /// completion that ended it. One batch's GPU work and the host's lateness to see it end, or + /// several seen complete at once. + pub unshared_waits_over_16ms_longest_runs_nanos: u64, + /// Of those waits, the ones whose longest run alone was over 16 ms: behind one long batch, + /// rather than many short ones. + pub unshared_waits_over_16ms_behind_one_long_run: u64, /// Runs in this process of the device's check of its GPU's idling between `VkQueue`s /// (`queue_switch_check.rs`), whatever they answered. pub queue_switch_checks_run: u64, @@ -8176,6 +8210,9 @@ impl Device { let [behind, unshared_behind] = (counters.behind_other_queues) .each_ref() .map(|tally| tally.read()); + let unshared_long_waits = (counters.unshared_long_waits) + .each_ref() + .map(|count| count.load(Ordering::Relaxed)); let not_inline = |why: NotInline| counters.passes_not_inline[why.index()].load(Ordering::Relaxed); let actions = |action: ActionsRefused| { @@ -8642,6 +8679,10 @@ impl Device { unshared_command_buffers_behind_other_queues_over_16ms: unshared_behind[1], unshared_command_buffers_behind_other_queues_over_33ms: unshared_behind[2], unshared_wait_behind_other_queues_longest_nanos: unshared_behind[3], + unshared_waits_over_16ms_batches_ahead: unshared_long_waits[0], + unshared_waits_over_16ms_most_batches_ahead: unshared_long_waits[1], + unshared_waits_over_16ms_longest_runs_nanos: unshared_long_waits[2], + unshared_waits_over_16ms_behind_one_long_run: unshared_long_waits[3], queue_switch_checks_run: counters.queue_switch_checks_run.load(Ordering::Relaxed), queue_switch_checks_recalled: counters .queue_switch_checks_recalled diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index da75c3f31..813a684c9 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3324,6 +3324,10 @@ field metal2vulkan-runtime::WorkCounts.unshared_command_buffers_behind_other_que field metal2vulkan-runtime::WorkCounts.unshared_command_buffers_behind_other_queues_over_16ms pub unshared_command_buffers_behind_other_queues_over_16ms: u64 field metal2vulkan-runtime::WorkCounts.unshared_command_buffers_behind_other_queues_over_33ms pub unshared_command_buffers_behind_other_queues_over_33ms: u64 field metal2vulkan-runtime::WorkCounts.unshared_wait_behind_other_queues_longest_nanos pub unshared_wait_behind_other_queues_longest_nanos: u64 +field metal2vulkan-runtime::WorkCounts.unshared_waits_over_16ms_batches_ahead pub unshared_waits_over_16ms_batches_ahead: u64 +field metal2vulkan-runtime::WorkCounts.unshared_waits_over_16ms_behind_one_long_run pub unshared_waits_over_16ms_behind_one_long_run: u64 +field metal2vulkan-runtime::WorkCounts.unshared_waits_over_16ms_longest_runs_nanos pub unshared_waits_over_16ms_longest_runs_nanos: u64 +field metal2vulkan-runtime::WorkCounts.unshared_waits_over_16ms_most_batches_ahead pub unshared_waits_over_16ms_most_batches_ahead: u64 field metal2vulkan-runtime::WorkCounts.untouched_passes_skipped pub untouched_passes_skipped: u64 field metal2vulkan-runtime::WorkCounts.upload_chunks_in_device_memory pub upload_chunks_in_device_memory: u64 field metal2vulkan-runtime::WorkCounts.uses_noted_covered pub uses_noted_covered: u64