Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

perf(canvas): report how long the GPU spends on a composite (#7275)

skylar taylor-barrick5c7c8479234d
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 3d60adaf1..e99dc5341 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -42,6 +42,7 @@ mod fx;
pub mod health;
pub mod plan;
mod prefix;
+pub mod timing;
use std::collections::HashMap;
use std::num::NonZeroU64;
@@ -55,6 +56,7 @@ use photocraft_raster::{Surface, Tile};
pub use health::{DeviceHealth, Fault};
pub use plan::{Kernel, Plan, Role, Unsupported, plan};
+pub use timing::{GpuTimer, GpuTiming};
/// Accumulator format for intermediate buffers. Full float: discontinuous operations
/// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as
@@ -107,6 +109,12 @@ pub struct ChunkOut<'a> {
/// What a render did (for profiling and tests).
#[derive(Clone, Copy, Debug, Default)]
pub struct Stats {
+ /// How long the GPU spent executing a composite, once its timestamps came back. Because the
+ /// readback is asynchronous this belongs to an *earlier* render than the one returning it
+ /// (it carries that render's own pixel count, so the two are never confused), and it is
+ /// `None` unless [`Compositor::measure_gpu_time`] is on and a measurement has landed.
+ /// Always `None` from [`Compositor::encode`], which submits nothing of its own.
+ pub gpu_time: Option<timing::GpuTiming>,
pub passes: usize,
pub chunks: usize,
pub slots: u32,
@@ -474,6 +482,9 @@ pub struct Compositor {
cmyk: u64,
/// The device's health (see [`Compositor::set_health`]); `None` = assumed healthy.
health: Option<DeviceHealth>,
+ /// Timestamp queries measuring how long the GPU spends on a refresh (see
+ /// [`Compositor::measure_gpu_time`]); `None` = not measured.
+ timer: Option<timing::GpuTimer>,
}
fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
@@ -709,6 +720,7 @@ impl Compositor {
effect_maps: map_error.is_none(),
cmyk: 0,
health: None,
+ timer: None,
}
.with_texture_limit(device.limits().max_texture_dimension_2d)
}
@@ -961,6 +973,41 @@ impl Compositor {
self.health.as_ref().and_then(DeviceHealth::fault)
}
+ /// Measure how long the GPU spends executing each [`Compositor::render`], with timestamp
+ /// queries read back asynchronously (nothing waits for the GPU). Returns whether the device
+ /// supports it: without [`timing::FEATURES`] there is no measurement at all, and callers
+ /// report no GPU time rather than the encode-and-submit cost `composite_ms` already is.
+ ///
+ /// A measurement arrives a frame or two after the refresh it belongs to, so it carries that
+ /// refresh's own pixel count; take it with [`Compositor::take_gpu_timing`].
+ pub fn measure_gpu_time(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool {
+ // `PHOTOCRAFT_NO_GPU_TIMING` turns it off: a kill switch for a driver whose timestamp
+ // queries misbehave, and the control arm for measuring what the queries themselves
+ // cost — the device is identical either way, so only the instrumentation varies.
+ if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() {
+ return false;
+ }
+ if self.timer.is_none() {
+ self.timer = timing::GpuTimer::new(device, queue);
+ }
+ self.timer.is_some()
+ }
+
+ /// Whether [`Compositor::measure_gpu_time`] is on for this compositor.
+ pub fn measures_gpu_time(&self) -> bool {
+ self.timer.is_some()
+ }
+
+ /// The most recent finished GPU measurement, leaving none behind (a stale number is never
+ /// reported twice as new). `None` while unmeasured, unsupported, or still in flight.
+ ///
+ /// [`Compositor::render`] already drains this into [`Stats::gpu_time`], so the app never
+ /// calls it; it is how a bench or a test collects a measurement without issuing another
+ /// render to carry it.
+ pub fn take_gpu_timing(&mut self) -> Option<timing::GpuTiming> {
+ self.timer.as_mut().and_then(timing::GpuTimer::take)
+ }
+
/// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is
/// still open; the chunk texture is reused afterwards, so the sink must record any copies
/// or passes that read it into the given encoder. Submits the work before returning; a
@@ -976,8 +1023,47 @@ impl Compositor {
) -> Result<Stats, Unsupported> {
let result = scoped_work(device, self.health.is_some(), || {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") });
- let stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true)?;
+ if self.timer.as_ref().is_some_and(timing::GpuTimer::busy) {
+ // The readback map completes on a poll. The app polls every frame, but a
+ // non-blocking poll here keeps the measurements coming whatever the caller does.
+ match &self.health {
+ Some(h) => h.poll(device),
+ None => {
+ let _ = device.poll(wgpu::PollType::Poll);
+ }
+ }
+ }
+ // Whatever came back since the last render travels out with this one's stats, so
+ // nothing has to reach back into the compositor for it afterwards.
+ let landed = self.timer.as_mut().and_then(timing::GpuTimer::take);
+ if let Some(t) = &mut self.timer {
+ let r = region.intersect(&doc.bounds());
+ t.start(&mut encoder, r.width() as u64 * r.height() as u64);
+ }
+ let mut stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true);
+ if let Ok(s) = &mut stats {
+ s.gpu_time = landed;
+ }
+ if let Some(t) = &mut self.timer {
+ // A refresh that failed part way measures nothing: its spans describe work the
+ // caller is about to redo on the CPU.
+ match stats {
+ Ok(_) => t.finish(&mut encoder),
+ Err(_) => {
+ t.cancel();
+ // The refresh is lost, but a measurement that came back with it is not:
+ // hand it to the next render rather than drop it on the fallback path.
+ if let Some(landed) = landed {
+ t.restore(landed);
+ }
+ }
+ }
+ }
+ let stats = stats?;
queue.submit([encoder.finish()]);
+ if let Some(t) = &mut self.timer {
+ t.submitted();
+ }
Ok(stats)
});
if result.is_err() {
@@ -1129,7 +1215,7 @@ impl Compositor {
stats.evicted += evicted;
freed += bytes;
if flush && (self.staged >= flush_bytes || work >= FLUSH_WORK || freed >= flush_bytes || self.recorded >= FLUSH_OPS) {
- submit_batch(device, queue, encoder, self.health.as_ref(), &mut last_submit);
+ submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit);
self.staged = 0;
self.recorded = 0;
work = 0;
@@ -1404,7 +1490,7 @@ impl Compositor {
if self.recorded >= FLUSH_OPS
&& let Some(last) = batch.as_deref_mut()
{
- submit_batch(device, queue, encoder, self.health.as_ref(), last);
+ submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), last);
self.staged = 0;
self.recorded = 0;
stats.flushes += 1;
@@ -2039,9 +2125,14 @@ fn submit_batch(
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
health: Option<&DeviceHealth>,
+ timer: Option<&mut timing::GpuTimer>,
last: &mut Option<wgpu::SubmissionIndex>,
) {
- let done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") }));
+ let mut done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") }));
+ if let Some(t) = timer {
+ // One refresh, several command buffers: the measurement spans all of them.
+ t.split(&mut done, encoder);
+ }
let prev = last.replace(queue.submit([done.finish()]));
#[cfg(not(target_arch = "wasm32"))]
if let Some(prev) = prev {
diff --git a/crates/gpu/src/timing.rs b/crates/gpu/src/timing.rs
new file mode 100644
index 000000000..e79548d84
--- /dev/null
+++ b/crates/gpu/src/timing.rs
@@ -0,0 +1,308 @@
+//! GPU execution time of a composite (#7186), measured with wgpu timestamp queries.
+//!
+//! `GpuCanvas::refresh` reports `composite_ms`, the CPU cost of *encoding and submitting* the
+//! composite. That is not the cost of running it: at 24 MP the encode costs ~7.7 ms and the GPU
+//! then spends ~171 ms finishing the work, so every consumer of `composite_ms` under-reports a
+//! GPU-bound canvas by more than an order of magnitude and cannot see a regression that moves
+//! work onto the GPU.
+//!
+//! Waiting for the GPU to report the true number would serialise the two processors and make the
+//! app slower, so this measures instead of waiting: a timestamp is written on the GPU timeline at
+//! the start and end of every command encoder a refresh submits, and the values are read back
+//! asynchronously. The sum of the spans is the time the GPU spent executing that refresh, with
+//! the CPU encoding gaps between submissions excluded. Nothing blocks; the numbers simply arrive
+//! a frame or two later, so each measurement carries the pixel count of the refresh it belongs to
+//! and is never attributed to whichever refresh happens to be in flight when it lands.
+//!
+//! **What it does not count.** The spans run between bottom-of-pipe timestamps inside the
+//! refresh's own command buffers. Two kinds of GPU work fall outside them: queue-level uploads
+//! (`Queue::write_texture`), which wgpu executes in its own command buffer before ours, and
+//! whatever the GPU still does after the final timestamp retires — the end-of-batch writeback of
+//! the render targets. Measured against a waited-for wall clock on Intel UHD P630 / Mesa, with
+//! no uploads outstanding, the uncounted remainder is **~5 % of the reported time**, and it is
+//! proportional to the composite rather than a fixed submit latency (1.0 ms at 6 MP, 4.5 ms at
+//! 24 MP, 7.6 ms at 42.6 MP, against 21 / 83 / 158 ms reported). So the number is a slight
+//! under-report of the GPU's total contribution, by a few per cent rather than the ~22x of the
+//! encode-and-submit time it replaces.
+//!
+//! **What it costs.** Nothing measurable. The same refresh on the same device with
+//! `PHOTOCRAFT_NO_GPU_TIMING` set waits 88.1 ms against 87.9 ms measured — a difference of
+//! −0.2 ms on an ~88 ms refresh, i.e. inside the noise of a shared host. Per refresh the
+//! queries add two timestamp writes (two more per flush), one resolve and one copy of at most
+//! 1 KiB, a `map_async` and an `Arc` allocation; the query set and both buffers are allocated
+//! once per compositor and are size-independent, so a resize reallocates nothing.
+//!
+//! The measurement is *optional by construction*. Without `TIMESTAMP_QUERY` and
+//! `TIMESTAMP_QUERY_INSIDE_ENCODERS` on the device (older drivers, most browsers, the Noop
+//! backend), [`GpuTimer::new`] returns `None` and callers report no GPU time at all rather than a
+//! plausible wrong number — reporting a plausible wrong number is the failure this fixes.
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU8, Ordering};
+
+/// The GPU execution time of one composite, with the refresh it measured.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct GpuTiming {
+ /// Time the GPU spent executing the refresh's command buffers (ms). Excludes queue-level
+ /// uploads, which run in wgpu's own command buffer ahead of ours, and the end-of-batch work
+ /// after the last timestamp: see the module doc for the size of that (~5 % here, more on a
+ /// refresh that uploads).
+ pub ms: f64,
+ /// Pixels that refresh composited (so a late measurement stays interpretable).
+ pub px: u64,
+ /// Command buffers the refresh submitted (1 unless it flushed).
+ pub spans: u32,
+}
+
+/// Device features [`GpuTimer`] needs.
+pub const FEATURES: wgpu::Features = wgpu::Features::TIMESTAMP_QUERY.union(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS);
+
+/// Spans one measurement may hold. A refresh submits once per flush; a 200 MP document flushes a
+/// handful of times, so this is far above anything real. A measurement that would exceed it is
+/// dropped rather than truncated (a truncated sum is exactly the under-report being fixed).
+const SPANS: u32 = 64;
+/// Any span total above this is a wrapped or garbage timestamp, not a composite.
+const SANE_MS: f64 = 600_000.0;
+
+/// Readback state of the buffer holding the resolved timestamps.
+const UNMAPPED: u8 = 0;
+const MAPPED: u8 = 1;
+const FAILED: u8 = 2;
+
+/// Timestamp queries for one compositor, reused for every refresh.
+///
+/// At most one measurement is in flight: while the last one is still being read back a refresh
+/// goes unmeasured, which costs a sample rather than correctness.
+pub struct GpuTimer {
+ set: wgpu::QuerySet,
+ /// Resolved timestamps (`QUERY_RESOLVE | COPY_SRC`).
+ resolve: wgpu::Buffer,
+ /// Host-visible copy of `resolve` (`MAP_READ | COPY_DST`).
+ read: wgpu::Buffer,
+ /// Nanoseconds per timestamp tick, as the queue reports it.
+ period_ns: f32,
+ /// Timestamps written into the current recording.
+ written: u32,
+ /// Whether a span is open (a start timestamp waiting for its end).
+ open: bool,
+ /// Pixels of the recording in progress.
+ px: u64,
+ /// The recording overflowed [`SPANS`]: finish without resolving.
+ overflowed: bool,
+ /// The recording in progress has already had command buffers submitted (it flushed), so its
+ /// query slots may still be in use by the GPU.
+ flushed: bool,
+ /// A recording was abandoned after it had already submitted timestamps. Writing a query
+ /// again resets that slot (wgpu-core resets per write), and resetting one an in-flight
+ /// submission is still writing is undefined, with no way to learn when it has drained.
+ /// That only happens when a refresh fails after a flush, which on this path means the
+ /// device faulted and the canvas is about to drop to the CPU compositor anyway, so
+ /// measuring simply stops: no number, which is the contract everywhere else here.
+ stopped: bool,
+ /// Timestamps and pixels of the measurement being read back, and its readback flag.
+ in_flight: Option<(u32, u64, Arc<AtomicU8>)>,
+ /// [`Self::finish`] recorded a readback that [`Self::submitted`] has yet to map. Without
+ /// this, a refresh that starts before the last measurement lands would map the readback
+ /// buffer a second time while the first map is still pending, which wgpu rejects.
+ unmapped: bool,
+ /// The most recent completed measurement, until a caller takes it.
+ ready: Option<GpuTiming>,
+}
+
+impl std::fmt::Debug for GpuTimer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("GpuTimer").field("recording", &self.open).field("in_flight", &self.in_flight.is_some()).field("ready", &self.ready).finish()
+ }
+}
+
+impl GpuTimer {
+ /// A timer for `device`, or `None` when it has no timestamp queries (the caller then reports
+ /// no GPU time, never an estimate).
+ pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Self> {
+ if !device.features().contains(FEATURES) {
+ return None;
+ }
+ let period_ns = queue.get_timestamp_period();
+ if !period_ns.is_finite() || period_ns <= 0.0 {
+ return None;
+ }
+ let bytes = u64::from(SPANS) * 2 * 8;
+ Some(Self {
+ set: device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("pc_compose_time"), ty: wgpu::QueryType::Timestamp, count: SPANS * 2 }),
+ resolve: device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("pc_compose_time_resolve"),
+ size: bytes,
+ usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
+ mapped_at_creation: false,
+ }),
+ read: device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("pc_compose_time_read"),
+ size: bytes,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ }),
+ period_ns,
+ written: 0,
+ open: false,
+ px: 0,
+ overflowed: false,
+ flushed: false,
+ stopped: false,
+ in_flight: None,
+ unmapped: false,
+ ready: None,
+ })
+ }
+
+ /// Start measuring a refresh of `px` pixels, opening its first span in `encoder`. Does
+ /// nothing while a previous measurement is still being read back (that refresh goes
+ /// unmeasured) — call [`Self::collect`] first to give it the chance to land.
+ pub fn start(&mut self, encoder: &mut wgpu::CommandEncoder, px: u64) {
+ if self.stopped || self.in_flight.is_some() || self.open {
+ return;
+ }
+ self.written = 0;
+ self.overflowed = false;
+ self.flushed = false;
+ self.px = px;
+ self.open = true;
+ self.stamp(encoder);
+ }
+
+ /// Close the span in `done` and open the next in `next`: one refresh that submits several
+ /// command buffers is one measurement, summed over them.
+ pub fn split(&mut self, done: &mut wgpu::CommandEncoder, next: &mut wgpu::CommandEncoder) {
+ if !self.open {
+ return;
+ }
+ self.stamp(done);
+ self.stamp(next);
+ self.flushed = true;
+ }
+
+ /// Close the last span and record the resolve and readback copy into `encoder`, which the
+ /// caller is about to submit. Call [`Self::submitted`] once it has.
+ pub fn finish(&mut self, encoder: &mut wgpu::CommandEncoder) {
+ if !self.open {
+ return;
+ }
+ self.stamp(encoder);
+ self.open = false;
+ let count = self.written;
+ if self.overflowed || count < 2 || !count.is_multiple_of(2) {
+ self.abandon();
+ return;
+ }
+ let bytes = u64::from(count) * 8;
+ encoder.resolve_query_set(&self.set, 0..count, &self.resolve, 0);
+ encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, bytes);
+ self.in_flight = Some((count, self.px, Arc::new(AtomicU8::new(UNMAPPED))));
+ self.unmapped = true;
+ self.written = 0;
+ // This recording is over: its slots are protected by `in_flight` until the readback
+ // lands, not by `flushed`. Leaving `flushed` set would let a later refresh that
+ // recorded nothing (because `start` found the readback still in flight) stop measuring
+ // for good when it failed, on the strength of this recording's flush.
+ self.flushed = false;
+ }
+
+ /// Map the readback buffer after the caller submitted the encoder [`Self::finish`] wrote
+ /// into. The map completes on a later device poll; nothing blocks here.
+ pub fn submitted(&mut self) {
+ if !self.unmapped {
+ return;
+ }
+ self.unmapped = false;
+ let Some((count, _, flag)) = &self.in_flight else { return };
+ let (bytes, flag) = (u64::from(*count) * 8, flag.clone());
+ self.read.slice(0..bytes).map_async(wgpu::MapMode::Read, move |r| {
+ flag.store(if r.is_ok() { MAPPED } else { FAILED }, Ordering::Release);
+ });
+ }
+
+ /// Abandon the recording in progress (the refresh failed part way, so its spans mean
+ /// nothing).
+ pub fn cancel(&mut self) {
+ self.open = false;
+ self.abandon();
+ }
+
+ /// Drop the recording in progress. Once its timestamps have reached the GPU its slots can't
+ /// be reused safely, so measuring stops for good rather than resetting a live query.
+ fn abandon(&mut self) {
+ self.stopped |= self.flushed;
+ self.written = 0;
+ self.overflowed = false;
+ self.flushed = false;
+ }
+
+ /// Whether a measurement is being read back (so this refresh won't be measured).
+ pub fn busy(&self) -> bool {
+ self.in_flight.is_some()
+ }
+
+ /// Read back a finished measurement if the map completed, and return whatever is ready.
+ /// Cheap and non-blocking; callers poll it per refresh or per frame.
+ pub fn collect(&mut self) -> Option<GpuTiming> {
+ if let Some((count, px, flag)) = &self.in_flight {
+ match flag.load(Ordering::Acquire) {
+ MAPPED => {
+ let (count, px) = (*count, *px);
+ self.ready = self.value(count, px);
+ self.read.unmap();
+ self.in_flight = None;
+ }
+ FAILED => {
+ self.in_flight = None;
+ }
+ _ => {}
+ }
+ }
+ self.ready
+ }
+
+ /// Put a measurement back after a caller took it but could not use it (its refresh failed),
+ /// so the sample is reported by the next one instead of being lost on the fallback path.
+ /// A measurement that has landed since wins: it is the newer of the two.
+ pub fn restore(&mut self, t: GpuTiming) {
+ self.ready.get_or_insert(t);
+ }
+
+ /// Take the most recent completed measurement, leaving none behind, so a stale number is
+ /// never reported twice as if it were new.
+ pub fn take(&mut self) -> Option<GpuTiming> {
+ self.collect();
+ self.ready.take()
+ }
+
+ /// Sum the resolved spans of a mapped readback.
+ fn value(&self, count: u32, px: u64) -> Option<GpuTiming> {
+ let bytes = u64::from(count) * 8;
+ let view = self.read.slice(0..bytes).get_mapped_range().ok()?;
+ let mut ticks = 0u64;
+ for pair in view.as_chunks::<16>().0 {
+ let (a, b) = pair.split_at(8);
+ let start = u64::from_le_bytes(a.try_into().ok()?);
+ let end = u64::from_le_bytes(b.try_into().ok()?);
+ // A driver that reset or wrapped its timer gives an end before its start: the whole
+ // measurement is then unusable, and no number is better than a wrong one.
+ if end < start {
+ return None;
+ }
+ ticks += end - start;
+ }
+ drop(view);
+ let ms = ticks as f64 * f64::from(self.period_ns) / 1.0e6;
+ (ms.is_finite() && ms < SANE_MS).then_some(GpuTiming { ms, px, spans: count / 2 })
+ }
+
+ /// Write one timestamp, noting an overflow instead of wrapping round the query set.
+ fn stamp(&mut self, encoder: &mut wgpu::CommandEncoder) {
+ if self.written >= SPANS * 2 {
+ self.overflowed = true;
+ return;
+ }
+ encoder.write_timestamp(&self.set, self.written);
+ self.written += 1;
+ }
+}
diff --git a/crates/gpu/tests/timing.rs b/crates/gpu/tests/timing.rs
new file mode 100644
index 000000000..24c205725
--- /dev/null
+++ b/crates/gpu/tests/timing.rs
@@ -0,0 +1,282 @@
+//! The canvas timing must measure GPU *execution*, not encode-and-submit (#7186).
+//!
+//! `composite_ms` reports the CPU cost of handing the composite to the driver, which on a
+//! GPU-bound refresh is a small fraction of what the refresh costs — at 24 MP it read 7.7 ms for
+//! work that took ~171 ms. `Compositor::measure_gpu_time` adds timestamp queries whose spans are
+//! summed into a [`GpuTiming`]. This test pins that down from both sides: the measurement must
+//! track the waited-for wall clock and must be several times the submit time, so an accidental
+//! return to timing the submit fails it.
+//!
+//! **Hardware only.** A software rasteriser composites on the CPU, where submit and execution
+//! are the same work, so the whole premise disappears and the test would pass on a bug. It
+//! therefore refuses to run on a CPU adapter and says so, as every GPU timing measurement in
+//! this project must (egui_kittest's `default_wgpu_setup` prefers CPU adapters on purpose).
+
+use std::time::Instant;
+
+use photocraft_color::{BlendMode, Color, ColorMode, SampleType};
+use photocraft_doc::{Document, Layer, Size};
+use photocraft_geom::Rect;
+use photocraft_gpu::{Compositor, DeviceHealth, GpuTiming, timing};
+
+/// Pixels in `r`, as the compositor counts them.
+fn area(r: Rect) -> u64 {
+ r.width() as u64 * r.height() as u64
+}
+
+fn block_on<F: std::future::Future>(f: F) -> F::Output {
+ let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
+ let mut f = std::pin::pin!(f);
+ loop {
+ if let std::task::Poll::Ready(v) = f.as_mut().poll(&mut cx) {
+ return v;
+ }
+ std::thread::yield_now();
+ }
+}
+
+/// A real GPU with timestamp queries, or `None` with the reason printed.
+fn gpu() -> Option<(wgpu::Device, wgpu::Queue, Compositor)> {
+ let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() };
+ let Ok(adapter) = block_on(wgpu::Instance::default().request_adapter(&options)) else {
+ eprintln!("SKIP gpu timing: no adapter");
+ return None;
+ };
+ let info = adapter.get_info();
+ if info.device_type == wgpu::DeviceType::Cpu || info.backend == wgpu::Backend::Noop {
+ // Not a skip we can be quiet about: a GPU timing test on llvmpipe measures nothing.
+ eprintln!("SKIP gpu timing: {} is a software adapter, which cannot show a GPU/CPU split", info.name);
+ return None;
+ }
+ if !adapter.features().contains(timing::FEATURES) {
+ eprintln!("SKIP gpu timing: {} has no timestamp queries", info.name);
+ return None;
+ }
+ let descriptor = wgpu::DeviceDescriptor { required_features: timing::FEATURES, ..Default::default() };
+ let Ok((device, queue)) = block_on(adapter.request_device(&descriptor)) else {
+ eprintln!("SKIP gpu timing: no device with timestamp queries");
+ return None;
+ };
+ let mut comp = Compositor::new(&device);
+ assert!(comp.measure_gpu_time(&device, &queue), "the device has the features, so the timer must build");
+ eprintln!("gpu timing on {} ({:?}, {:?})", info.name, info.device_type, info.backend);
+ Some((device, queue, comp))
+}
+
+fn rnd(seed: u32, i: u32) -> f32 {
+ let mut h = seed.wrapping_mul(0x9e37_79b9) ^ i.wrapping_mul(0x85eb_ca6b);
+ h ^= h >> 13;
+ h = h.wrapping_mul(0xc2b2_ae35);
+ h ^= h >> 16;
+ (h & 0xffff) as f32 / 65535.0
+}
+
+/// A document whose composite is clearly GPU-bound: several full-canvas blended photo layers.
+fn document(size: Size) -> Document {
+ let mut doc = Document::with_background("timing", size, ColorMode::Rgb, SampleType::U8, Color::rgba(0.5, 0.5, 0.5, 1.0));
+ let fmt = doc.pixel_format();
+ let rect = Rect::from_xywh(0, 0, size.width, size.height);
+ for (i, blend) in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Overlay, BlendMode::SoftLight].into_iter().enumerate() {
+ let mut layer = Layer::raster(format!("l{i}"), fmt);
+ let channels = fmt.channels();
+ let px: Vec<f32> = (0..rect.width() * rect.height()).flat_map(|p| (0..channels).map(move |c| rnd(7 + i as u32 * 131 + c as u32 * 7919, p))).collect();
+ if let Some(s) = layer.surface_mut() {
+ s.write_region(rect, &px);
+ }
+ layer.blend = blend;
+ layer.opacity = 0.8;
+ doc.layers.push(layer);
+ }
+ doc
+}
+
+/// Render `region` and return (submit ms, waited-for wall ms, the measurement).
+fn measure(device: &wgpu::Device, queue: &wgpu::Queue, comp: &mut Compositor, doc: &Document, region: Rect) -> (f64, f64, Option<GpuTiming>) {
+ let t0 = Instant::now();
+ comp.render(device, queue, doc, region, |_, _| {}).expect("the document composites on the GPU");
+ let submit_ms = t0.elapsed().as_secs_f64() * 1000.0;
+ let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
+ let wall_ms = t0.elapsed().as_secs_f64() * 1000.0;
+ // The readback map completes on a poll, and its callback runs on the next one.
+ let mut timing = None;
+ for _ in 0..4 {
+ timing = comp.take_gpu_timing();
+ if timing.is_some() {
+ break;
+ }
+ let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
+ }
+ (submit_ms, wall_ms, timing)
+}
+
+#[test]
+fn gpu_time_tracks_execution_not_submission() {
+ let Some((device, queue, mut comp)) = gpu() else { return };
+ let size = Size::new(3000, 2000);
+ let doc = document(size);
+ let full = Rect::from_xywh(0, 0, size.width, size.height);
+
+ // Warm the residency and pipelines: the first refresh uploads every layer.
+ let _ = measure(&device, &queue, &mut comp, &doc, full);
+
+ // Best of three, by the smallest encode. Everything below is a ratio against `submit_ms`,
+ // and CPU contention on a shared machine only ever inflates it — one run that happened to
+ // encode behind a busy scheduler (8.2 ms against a typical 1.0 ms) failed the comparison
+ // while the measurement itself was right. The GPU side is unaffected by that contention,
+ // so taking the least-disturbed encode tests the same property without the false failure.
+ let mut best: Option<(f64, f64, Option<GpuTiming>)> = None;
+ for _ in 0..3 {
+ let run = measure(&device, &queue, &mut comp, &doc, full);
+ if run.2.is_some() && best.as_ref().is_none_or(|b| run.0 < b.0) {
+ best = Some(run);
+ }
+ }
+ let (submit_ms, wall_ms, timing) = best.expect("at least one of three refreshes reports a GPU time");
+ let t = timing.expect("a hardware device with timestamp queries must report a GPU time");
+ eprintln!("full {}x{}: submit {submit_ms:.1} ms, waited wall {wall_ms:.1} ms, gpu {:.1} ms", size.width, size.height, t.ms);
+
+ assert_eq!(t.px, area(full), "the measurement carries the pixels of the refresh it measured");
+ assert!(t.spans >= 1, "at least one command buffer was timed");
+
+ // The premise: on this adapter the refresh really is dominated by GPU execution. A machine
+ // fast enough that it isn't cannot tell the two timings apart, so say so instead of failing.
+ if wall_ms < 3.0 * submit_ms {
+ eprintln!("SKIP the comparison: this GPU finishes a 6 MP composite in {wall_ms:.1} ms against {submit_ms:.1} ms of encoding");
+ return;
+ }
+
+ // Timing the submit again (the bug) would report roughly `submit_ms` here.
+ assert!(t.ms > 3.0 * submit_ms, "gpu time {:.1} ms looks like the submit time {submit_ms:.1} ms, not the execution", t.ms);
+ // …and it must be the real execution, not merely a bigger number: the waited-for wall clock
+ // is encode + execute, so the GPU span sits below it and accounts for most of it.
+ assert!(t.ms <= wall_ms * 1.25, "gpu time {:.1} ms exceeds the whole waited-for refresh {wall_ms:.1} ms", t.ms);
+ assert!(t.ms >= (wall_ms - submit_ms) * 0.5, "gpu time {:.1} ms is far below the {:.1} ms the refresh waited", t.ms, wall_ms - submit_ms);
+
+ // A quarter of the canvas is a quarter of the per-pixel work: a constant or a stale value
+ // would not follow it.
+ let quarter = Rect::from_xywh(0, 0, size.width / 2, size.height / 2);
+ let (_, _, small) = measure(&device, &queue, &mut comp, &doc, quarter);
+ let s = small.expect("the smaller refresh is measured too");
+ eprintln!("quarter: gpu {:.1} ms for {} px against {:.1} ms for {} px", s.ms, s.px, t.ms, t.px);
+ assert_eq!(s.px, area(quarter));
+ assert!(s.ms < t.ms * 0.6, "a quarter-canvas refresh took {:.1} ms against the full canvas's {:.1} ms", s.ms, t.ms);
+}
+
+#[test]
+fn an_unmeasured_compositor_reports_nothing() {
+ let Some((device, queue, _)) = gpu() else { return };
+ let mut comp = Compositor::new(&device);
+ assert!(!comp.measures_gpu_time(), "timing is off until it is asked for");
+ let doc = document(Size::new(256, 256));
+ comp.render(&device, &queue, &doc, Rect::from_xywh(0, 0, 256, 256), |_, _| {}).expect("composites");
+ let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
+ assert_eq!(comp.take_gpu_timing(), None, "no measurement is reported rather than a wrong one");
+}
+
+#[test]
+fn a_refresh_that_submits_several_times_is_one_measurement() {
+ let Some((device, queue, mut comp)) = gpu() else { return };
+ // A budget far below the document's layer pages makes the refresh evict as it goes, which is
+ // what makes it submit in batches: the measurement must span all of them, not just the last.
+ comp.set_memory_budget(24 << 20);
+ let size = Size::new(3000, 2000);
+ let doc = document(size);
+ let full = Rect::from_xywh(0, 0, size.width, size.height);
+
+ let _ = measure(&device, &queue, &mut comp, &doc, full);
+ let (submit_ms, wall_ms, timing) = measure(&device, &queue, &mut comp, &doc, full);
+ let t = timing.expect("a batched refresh is measured like any other");
+ eprintln!("batched: {} command buffers, gpu {:.1} ms, submit {submit_ms:.1} ms, waited wall {wall_ms:.1} ms", t.spans, t.ms);
+ assert_eq!(t.px, area(full));
+ if t.spans < 2 {
+ eprintln!("SKIP the sum: this refresh still fit one command buffer");
+ return;
+ }
+ assert!(t.ms <= wall_ms * 1.25, "summed gpu time {:.1} ms exceeds the whole waited-for refresh {wall_ms:.1} ms", t.ms);
+ // What this bound excludes is summing only the last command buffer. A correct sum measures
+ // ~85 % of the waited-for GPU time here; the flush thresholds split on accumulated work, so
+ // no single buffer of the several carries much over half of it, and timing only the last
+ // would land near 40 %. 0.6 sits between the two with room on both sides for a machine
+ // whose split is less even than this one's.
+ assert!(
+ t.ms >= (wall_ms - submit_ms) * 0.6,
+ "summed gpu time {:.1} ms is far below the {:.1} ms the refresh waited: is only the last command buffer timed?",
+ t.ms,
+ wall_ms - submit_ms
+ );
+}
+
+#[test]
+fn refreshes_faster_than_the_readback_stay_valid() {
+ let Some((device, queue, mut comp)) = gpu() else { return };
+ // Refreshes arriving before the last measurement has been read back must simply go
+ // unmeasured. Mapping the readback buffer again while its first map is still pending is a
+ // validation error, and an unusable device drops the whole canvas to the CPU compositor.
+ let health = DeviceHealth::watch(&device);
+ comp.set_health(health.clone());
+ let size = Size::new(600, 400);
+ let doc = document(size);
+ let full = Rect::from_xywh(0, 0, size.width, size.height);
+ for i in 0..16 {
+ comp.render(&device, &queue, &doc, full, |_, _| {}).unwrap_or_else(|e| panic!("refresh {i} failed: {e}"));
+ }
+ let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
+ assert_eq!(comp.fault(), None, "hurried refreshes must not fault the device");
+ assert_eq!(health.errors(), 0, "no uncaptured wgpu errors");
+}
+
+/// A refresh that recorded nothing must not stop the timer for good. `finish` leaves the
+/// measurement's slots protected by the pending readback, not by `flushed`; if `flushed`
+/// survived a successful finish, the next refresh to fail while that readback was still in
+/// flight would set `stopped` on the strength of the *earlier* refresh's flush — even though it
+/// wrote no timestamps itself — and the compositor would silently never measure again.
+#[test]
+fn a_failed_refresh_that_recorded_nothing_keeps_the_timer_alive() {
+ let Some((device, queue, _)) = gpu() else { return };
+ let mut timer = timing::GpuTimer::new(&device, &queue).expect("the device has timestamp queries");
+
+ // A refresh that flushes once, then succeeds.
+ let mut first = device.create_command_encoder(&Default::default());
+ let mut second = device.create_command_encoder(&Default::default());
+ timer.start(&mut first, 1024);
+ timer.split(&mut first, &mut second);
+ queue.submit([first.finish()]);
+ timer.finish(&mut second);
+ queue.submit([second.finish()]);
+ timer.submitted();
+
+ // A later refresh fails before recording anything, because the readback is still in flight.
+ let mut third = device.create_command_encoder(&Default::default());
+ timer.start(&mut third, 2048);
+ timer.cancel();
+ drop(third);
+
+ // The first measurement still lands...
+ let mut first_timing = None;
+ for _ in 0..8 {
+ let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
+ first_timing = timer.take();
+ if first_timing.is_some() {
+ break;
+ }
+ }
+ let landed = first_timing.expect("the flushed measurement completes");
+ assert_eq!(landed.spans, 2, "both command buffers are one measurement");
+
+ // ...and the timer still measures afterwards, which is what the bug destroyed.
+ let mut next = device.create_command_encoder(&Default::default());
+ timer.start(&mut next, 4096);
+ timer.finish(&mut next);
+ queue.submit([next.finish()]);
+ timer.submitted();
+ let mut after = None;
+ for _ in 0..8 {
+ let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
+ after = timer.take();
+ if after.is_some() {
+ break;
+ }
+ }
+ let after = after.expect("the timer still measures after a refresh that recorded nothing");
+ assert_eq!(after.px, 4096, "the measurement belongs to the refresh that produced it");
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index d8d943c81..a5f1452dd 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1648,11 +1648,11 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible:
// An adjustment preview composited where the view was: catch up where it moved to.
if let Some(r) = crate::adjust_preview::uncovered(app, id, raw_key, visible) {
let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref());
- app.perf.record(r.kind, r.px, r.composite_ms, r.upload_ms);
+ app.perf.record_refresh(&r);
}
if let Some(r) = crate::adjust_preview::live_uncovered(app, id, raw_key, visible) {
let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref());
- app.perf.record(r.kind, r.px, r.composite_ms, r.upload_ms);
+ app.perf.record_refresh(&r);
}
return true;
}
@@ -1693,7 +1693,7 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible:
log::info!("{e}; using the CPU compositor");
}
if r.kind != crate::gpu_canvas::REFRESH_DEFERRED {
- app.perf.record(r.kind, r.px, r.composite_ms, r.upload_ms);
+ app.perf.record_refresh(&r);
}
if r.kind == "full" {
crate::notices::slow_cpu_refresh(app, id.0, r.composite_ms + r.upload_ms, r.fallback.as_deref());
@@ -2015,6 +2015,9 @@ fn ensure_adjust_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option
let (display, _) = canvas_display(app, &doc, None);
let r = gpu.refresh(key, &frame.doc, frame.damage, display.as_deref());
app.perf.record(if r.kind.starts_with("gpu") { "gpu-adjust-proxy" } else { "adjust-proxy" }, r.px, r.composite_ms, r.upload_ms);
+ if let Some(t) = r.gpu {
+ app.perf.record_gpu(t);
+ }
crate::adjust_preview::proxy_drawn(app, &frame);
}
Some((frame.k, key, size))
diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs
index 1770979db..65388d504 100644
--- a/crates/ui-egui/src/gpu_canvas.rs
+++ b/crates/ui-egui/src/gpu_canvas.rs
@@ -295,6 +295,15 @@ impl GpuCanvas {
}
}
+ /// Take any GPU measurement that has landed since the last call, without compositing
+ /// anything. [`Compositor::render`] carries measurements out in its stats, but a refresh is
+ /// the only thing that collects them, so the last refresh before the app goes idle would
+ /// never be reported. The frame loop calls this so it is.
+ pub fn take_gpu_timing(&self) -> Option<photocraft_gpu::GpuTiming> {
+ let mut r = self.rs.renderer.write();
+ r.callback_resources.get_mut::<Resources>()?.compositor.as_mut()?.take_gpu_timing()
+ }
+
/// GPU bytes the wgpu compositor holds: resident layer pages and caches (effect maps and
/// lower-stack chunks). Keep the scorecard's memory measurements inclusive of reuse.
pub fn compositor_bytes(&self) -> Option<(u64, usize)> {
@@ -472,6 +481,8 @@ impl GpuCanvas {
},
};
comp.set_health(self.health.clone());
+ // Measured, not waited for: the timestamps come back a frame or two later.
+ comp.measure_gpu_time(device, queue);
if let Some(b) = res.compositor_budget {
comp.set_memory_budget(b);
}
@@ -636,8 +647,10 @@ impl GpuCanvas {
Ok(stats) => {
out.kind = if damage.is_some() { "gpu-rect" } else { "gpu-full" };
out.px = region.width() as u64 * region.height() as u64;
+ // Encoding and submitting only: the GPU is still running this work.
out.composite_ms = now_ms() - t0;
out.uploads = stats.tiles_uploaded as u64;
+ out.gpu = stats.gpu_time;
return out;
}
Err(e) => out.fallback = Some(e.0),
@@ -876,6 +889,14 @@ pub struct Refresh {
pub upload_ms: f64,
/// Layer tiles the wgpu compositor uploaded.
pub uploads: u64,
+ /// How long the GPU spent executing a recent wgpu composite, once its timestamps came back
+ /// (a frame or two after that refresh, so usually an earlier one than this). It carries its
+ /// own pixel count and is never this refresh's unless they match. `None` when the device has
+ /// no timestamp queries, on the CPU compositor, and on wasm: no number at all is reported
+ /// rather than `composite_ms`, which measures encoding and submitting, not executing. It
+ /// leaves out layer-tile uploads (`uploads` above counts them), so a first refresh of a
+ /// document under-reports by more than the few per cent of a warm one.
+ pub gpu: Option<photocraft_gpu::GpuTiming>,
/// Why the wgpu compositor wasn't used.
pub fallback: Option<String>,
}
@@ -903,11 +924,42 @@ pub fn use_adapter_limits_with(setup: &mut egui_wgpu::WgpuSetup, on_adapter: imp
if let egui_wgpu::WgpuSetup::CreateNew(create) = setup {
create.device_descriptor = std::sync::Arc::new(move |adapter| {
on_adapter(adapter);
- wgpu::DeviceDescriptor { label: Some("photocraft wgpu device"), required_limits: device_limits(adapter), ..Default::default() }
+ device_descriptor(adapter)
});
}
}
+/// How the app asks for its device: egui's defaults, the adapter's texture and buffer size
+/// limits ([`device_limits`]), and timestamp queries where the adapter has them, so the canvas
+/// can report how long the GPU actually spends compositing ([`photocraft_gpu::GpuTimer`]).
+/// A bench or test that builds its own device should use this rather than [`device_limits`]
+/// alone, or it measures a device the app never creates. (`bevel_bench`, `fx_bench` and
+/// `interactive_bench` still call [`device_limits`] directly and so report no GPU time.)
+pub fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
+ wgpu::DeviceDescriptor {
+ label: Some("photocraft wgpu device"),
+ required_limits: device_limits(adapter),
+ required_features: timing_features(adapter),
+ ..Default::default()
+ }
+}
+
+/// The timestamp-query features when the adapter supports all of them, else none: asking for a
+/// feature an adapter lacks fails device creation, and a canvas without GPU timing is far better
+/// than no canvas.
+///
+/// `PHOTOCRAFT_NO_GPU_TIMING` suppresses the request as well as the timer
+/// ([`photocraft_gpu::Compositor::measure_gpu_time`]), so the variable also rescues a driver
+/// that advertises the features and then fails or misbehaves on device creation — not only one
+/// whose timestamps come back wrong.
+pub fn timing_features(adapter: &wgpu::Adapter) -> wgpu::Features {
+ let want = photocraft_gpu::timing::FEATURES;
+ if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() {
+ return wgpu::Features::empty();
+ }
+ if adapter.features().contains(want) { want } else { wgpu::Features::empty() }
+}
+
/// egui's base limits (WebGL2's on GL), clamped to adapter support, with its maximum texture and buffer sizes.
pub fn device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits {
device_limits_for(adapter.get_info().backend, adapter.limits())
@@ -938,7 +990,9 @@ pub struct Perf {
pub ui_ms: f64,
/// Worst UI frame of the last ~second (ms).
pub ui_max_ms: f64,
- /// Last canvas refresh: CPU composite (ms).
+ /// Last canvas refresh, CPU side (ms): the CPU composite on the CPU path, and on the GPU
+ /// path the cost of *encoding and submitting* the composite — not of running it, which is
+ /// `gpu_ms`.
pub composite_ms: f64,
/// Last canvas refresh: conversion + upload (ms).
pub upload_ms: f64,
@@ -950,6 +1004,16 @@ pub struct Perf {
pub gpu: bool,
/// Layer tiles uploaded by the last GPU composite.
pub gpu_uploads: u64,
+ /// How long the GPU spent executing a recent composite (ms), from timestamp queries read
+ /// back after the fact. `None` on the CPU compositor, on a device without timestamp queries
+ /// and on wasm — there is then no honest number to report, and `composite_ms` is not one.
+ /// Excludes layer-tile uploads and end-of-batch work (see `photocraft_gpu::timing`), so it
+ /// is a few per cent under the GPU's full share of a warm refresh and further under a cold
+ /// one.
+ pub gpu_ms: Option<f64>,
+ /// Pixels of the refresh `gpu_ms` measured, which is a frame or two behind
+ /// `last_refresh_px` and may be a different size.
+ pub gpu_ms_px: u64,
/// Why the last refresh fell back to the CPU compositor (None = GPU composited).
pub gpu_fallback: Option<String>,
/// Adapter, backend, driver and fallback state (Help › System Info).
@@ -1102,10 +1166,28 @@ impl Perf {
self.upload_ms = upload_ms;
if !kind.starts_with("gpu") {
self.gpu_uploads = 0;
+ // The CPU compositor did this one: there is no GPU time, and the last GPU
+ // refresh's would be read as this refresh's.
+ self.gpu_ms = None;
+ self.gpu_ms_px = 0;
} else {
self.gpu_fallback = None;
}
}
+
+ /// Record a canvas refresh and any GPU measurement that came back with it.
+ pub fn record_refresh(&mut self, r: &Refresh) {
+ self.record(r.kind, r.px, r.composite_ms, r.upload_ms);
+ if let Some(t) = r.gpu {
+ self.record_gpu(t);
+ }
+ }
+
+ /// Record a GPU composite measurement that came back (see [`photocraft_gpu::GpuTiming`]).
+ pub fn record_gpu(&mut self, t: photocraft_gpu::GpuTiming) {
+ self.gpu_ms = Some(t.ms);
+ self.gpu_ms_px = t.px;
+ }
pub fn span(&mut self, name: &'static str, ms: f64) {
self.spans.insert(name, (ms * 100.0).round() / 100.0);
}
@@ -2380,6 +2462,36 @@ mod mip_tests;
mod tests {
use super::*;
+ /// A GPU measurement arrives a frame or two after its refresh, so most GPU refreshes carry
+ /// none; the last one reported must stand until a newer one lands. A CPU refresh is
+ /// different: there is no GPU time at all then, and keeping the old number would show it as
+ /// this refresh's. Runs anywhere — the GPU timing tests need hardware and CI has none.
+ #[test]
+ fn a_gpu_measurement_stands_until_replaced_and_a_cpu_refresh_clears_it() {
+ let timing = |ms, px| photocraft_gpu::GpuTiming { ms, px, spans: 1 };
+ let refresh = |kind, gpu| Refresh { kind, gpu, ..Default::default() };
+ let mut perf = Perf::default();
+ assert_eq!(perf.gpu_ms, None, "nothing is reported before a measurement");
+
+ perf.record_refresh(&refresh("gpu-full", Some(timing(83.9, 24_000_000))));
+ assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000));
+
+ // The common case: a GPU refresh whose own measurement has not come back yet.
+ perf.record_refresh(&refresh("gpu-rect", None));
+ assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000), "the last measurement stands");
+
+ perf.record_refresh(&refresh("gpu-rect", Some(timing(11.2, 1_098_640))));
+ assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(11.2), 1_098_640), "a newer measurement replaces it");
+
+ // The CPU compositor did this one: the GPU number belongs to no refresh on screen.
+ perf.record_refresh(&refresh("full", None));
+ assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (None, 0), "a CPU refresh clears it rather than showing a stale one");
+
+ // And it comes back on the next GPU refresh that carries one.
+ perf.record_refresh(&refresh("gpu-full", Some(timing(42.0, 6_000_000))));
+ assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(42.0), 6_000_000));
+ }
+
#[test]
fn device_limits_support_v3d_shader_variable_limit() {
let supported = wgpu::Limits { max_texture_dimension_2d: 7680, max_inter_stage_shader_variables: 15, ..wgpu::Limits::default() };
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index f97c6968f..2c23a29e3 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -2119,6 +2119,18 @@ impl eframe::App for PhotocraftApp {
ctx.set_cursor_icon(egui::CursorIcon::Wait);
}
let ui_ms = gpu_canvas::now_ms() - t0;
+ // A GPU measurement lands a frame or two after the refresh it belongs to. Refreshes
+ // carry them out, but the last refresh before the app settles has none following it, so
+ // drain the timer here too or its number is never reported. Drain it either way: a
+ // measurement left sitting would surface later against an unrelated refresh. Report it
+ // only while the canvas is still on the GPU, since a CPU refresh clears `gpu_ms`
+ // precisely so a GPU number is never shown as that refresh's.
+ if let Some(gpu) = &self.gpu
+ && let Some(t) = gpu.take_gpu_timing()
+ && self.perf.last_refresh.starts_with("gpu")
+ {
+ self.perf.record_gpu(t);
+ }
self.perf.frame(ui_ms);
if self.stroke_trace.enabled() {
self.stroke_trace.canvas(self.perf.frame_refresh_ms);