cool profiling

This commit is contained in:
2026-10-06 23:55:43 +02:00
parent b560f6afd7
commit 6b2e738a22
4 changed files with 872 additions and 265 deletions
+454
View File
@@ -0,0 +1,454 @@
use std::fmt::Debug;
use std::iter::Peekable;
use std::ops::Deref;
use std::ops::DerefMut;
use egui::Sense;
use egui::Ui;
use wgpu::Buffer;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::Device;
use wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
use wgpu::QuerySet;
use wgpu::Queue;
macro_rules! begin_frame {
($encoder:ident) => {
let mut $encoder = $encoder.begin_frame(None);
};
($encoder:ident, $name:literal) => {
let mut $encoder = $encoder.begin_frame(Some(literal));
};
}
macro_rules! begin_scope {
($scope:ident, $name:literal) => {
let mut $scope = $scope.begin_scope($name);
};
}
pub(crate) use begin_frame;
pub(crate) use begin_scope;
pub struct ScopeEncoder<'enc, 'prof_enc>
{
encoder: &'prof_enc mut ProfilingEncoder<'enc>,
scope_index: usize,
}
pub struct Scope
{
name: &'static str,
start_index: QuerySetHandle,
end_index: Option<QuerySetHandle>,
children: Vec<usize>,
}
pub struct ProfilingEncoder<'enc>
{
device: Device,
encoder: &'enc mut CommandEncoder,
query_set_allocator: QuerySetAllocator,
scopes: Vec<Scope>,
index_stack: Vec<usize>,
}
pub struct GpuProfile
{
scopes: Vec<Scope>,
timestamps: Buffer,
}
pub struct Frame
{
pub name: &'static str,
pub children: Vec<usize>,
pub start_timestamp: u64,
pub end_timestamp: u64,
}
#[derive(Default)]
pub struct Profile
{
pub frames: Vec<Frame>,
}
impl<'enc> ProfilingEncoder<'enc>
{
pub fn new(device: &Device, encoder: &'enc mut CommandEncoder) -> Self
{
Self {
encoder,
query_set_allocator: QuerySetAllocator::new(device),
scopes: Vec::new(),
device: device.clone(),
index_stack: Vec::new(),
}
}
pub fn begin_frame<'prof_enc>(
&'prof_enc mut self,
frame_name: Option<&'static str>,
) -> ScopeEncoder<'enc, 'prof_enc>
{
let scope_index = self.begin_scope(None, frame_name.unwrap_or("Frame"));
self.index_stack.push(scope_index);
ScopeEncoder {
encoder: self,
scope_index,
}
}
fn begin_scope(&mut self, scope_index: Option<usize>, name: &'static str) -> usize
{
let begin_query = self.query_set_allocator.allocate();
self.query_set_allocator
.write_timestamp(self.encoder, &begin_query);
let scope = Scope {
name,
start_index: begin_query,
end_index: None,
children: Vec::new(),
};
let new_scope_index = self.scopes.len();
self.scopes.push(scope);
self.index_stack.push(new_scope_index);
// Add this new stack to parent
if let Some(scope_index) = scope_index
{
self.scopes[scope_index].children.push(new_scope_index);
}
new_scope_index
}
fn end_scope(&mut self, scope_index: usize)
{
let end_query = self.query_set_allocator.allocate();
self.query_set_allocator
.write_timestamp(self.encoder, &end_query);
let scope = &mut self.scopes[scope_index];
let pop = self.index_stack.pop().unwrap();
assert_eq!(
pop, scope_index,
"Scopes must be defined in a stack fashion."
);
scope.end_index = Some(end_query);
}
pub fn finish_profiler(self) -> GpuProfile
{
let timestamp_count = self.query_set_allocator.allocated_count();
let resolve_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ProfilingEncoder::resolve_buffer"),
size: size_of::<u64>() as u64 * timestamp_count as u64,
usage: BufferUsages::QUERY_RESOLVE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
self.query_set_allocator
.resolve_all(self.encoder, &resolve_buffer);
GpuProfile {
scopes: self.scopes,
timestamps: resolve_buffer,
}
}
}
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc>
{
pub fn begin_scope<'scope>(&'scope mut self, name: &'static str) -> ScopeEncoder<'enc, 'scope>
where
'prof_enc: 'scope,
{
let scope_index = self.encoder.begin_scope(Some(self.scope_index), name);
ScopeEncoder {
encoder: self.encoder,
scope_index,
}
}
pub fn end_scope(self)
{
drop(self);
}
}
impl<'enc, 'prof_enc> Drop for ScopeEncoder<'enc, 'prof_enc>
{
fn drop(&mut self)
{
self.encoder.end_scope(self.scope_index);
}
}
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
&mut *self.encoder
}
}
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc>
{
type Target = CommandEncoder;
fn deref(&self) -> &Self::Target
{
&*self.encoder
}
}
impl<'enc> DerefMut for ProfilingEncoder<'enc>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
self.encoder
}
}
impl<'enc> Deref for ProfilingEncoder<'enc>
{
type Target = CommandEncoder;
fn deref(&self) -> &Self::Target
{
self.encoder
}
}
struct QuerySetAllocator
{
device: Device,
current_size: u32,
current_id: u32,
query_sets: Vec<(u32, u32, QuerySet)>,
}
#[derive(PartialEq, Eq)]
struct QuerySetHandle(usize, u32, u32);
impl QuerySetHandle
{
pub fn index(&self) -> usize
{
self.2 as usize
}
}
impl PartialOrd for QuerySetHandle
{
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering>
{
Some(self.cmp(other))
}
}
impl Ord for QuerySetHandle
{
fn cmp(&self, other: &Self) -> std::cmp::Ordering
{
match self.0.cmp(&other.0)
{
core::cmp::Ordering::Equal =>
{}
ord => return ord,
}
self.1.cmp(&other.1)
}
}
impl QuerySetAllocator
{
pub fn new(device: &Device) -> Self
{
let current_size = 32;
let query_sets = vec![(
0,
current_size,
Self::new_query_set(device, current_size, 0),
)];
QuerySetAllocator {
query_sets,
current_size,
current_id: 0,
device: device.clone(),
}
}
pub fn allocated_count(&self) -> u32
{
self.query_sets
.iter()
.map(|(allocated, _, _)| *allocated)
.sum()
}
pub fn resolve_all(&self, encoder: &mut CommandEncoder, target: &Buffer)
{
let mut offset = 0;
for (allocated, _, query_set) in self.query_sets.iter()
{
encoder.resolve_query_set(query_set, 0..*allocated, target, offset);
offset += *allocated as u64 * size_of::<u64>() as u64;
}
}
pub fn allocate(&mut self) -> QuerySetHandle
{
// Check if allocation is possible
if self
.query_sets
.last()
.is_some_and(|(allocated, available, _)| allocated == available)
{
// No more room, allocate new query set
self.current_size *= 2;
self.query_sets.push((
0,
self.current_size,
Self::new_query_set(&self.device, self.current_size, self.query_sets.len()),
));
}
// Last allocation is guaranteed to have room
let (allocated, _available, _query_set) = self.query_sets.last_mut().unwrap();
let query_index = *allocated;
*allocated += 1;
let query_set_index = self.query_sets.len() - 1;
let id = self.current_id;
self.current_id += 1;
QuerySetHandle(query_set_index, query_index, id)
}
fn new_query_set(device: &Device, size: u32, index: usize) -> QuerySet
{
device.create_query_set(&wgpu::QuerySetDescriptor {
label: Some(format!("QuerySetAllocator::query_set_{index}").as_str()),
ty: wgpu::QueryType::Timestamp,
count: size,
})
}
fn write_timestamp(&mut self, encoder: &mut CommandEncoder, handle: &QuerySetHandle)
{
let query_set = &self.query_sets[handle.0].2;
encoder.write_timestamp(query_set, handle.1);
}
}
impl GpuProfile
{
pub fn read_back(
self,
device: &Device,
queue: &Queue,
mut callback: impl FnMut(Profile) + Send + Sync + 'static,
)
{
// Readback timestamps
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&self.timestamps.slice(..),
move |buffer| {
let buffer = buffer.unwrap();
let timestamps: Vec<u64> = bytemuck::pod_collect_to_vec(&buffer);
let frames = self
.scopes
.into_iter()
.map(|scope| Frame {
name: scope.name,
children: scope.children,
start_timestamp: timestamps[scope.start_index.index()],
end_timestamp: timestamps[scope.end_index.unwrap().index()],
})
.collect::<Vec<_>>();
callback(Profile { frames });
},
);
}
}
impl Profile
{
pub fn to_display_string(&self, q: f32) -> String
{
let mut str = String::new();
self.frames[0].build_string(&self.frames, 0, q, &mut str);
str
}
pub fn show(&self, ui: &mut Ui, q: f32)
{
if !self.frames.is_empty()
{
self.frames[0].show(ui, q, &self.frames);
}
}
}
impl Frame
{
fn time(&self, q: f32) -> f32
{
(self.end_timestamp - self.start_timestamp) as f32 * q
}
fn build_string(&self, frames: &Vec<Frame>, depth: usize, q: f32, str: &mut String)
{
let mut depth_string = String::new();
(0..depth).for_each(|_| depth_string.push_str(" "));
let time = (self.end_timestamp - self.start_timestamp) as f32 * q;
str.push_str(&format!("{depth_string}{}: {:.2}\n", self.name, time));
self.children
.iter()
.for_each(|c| frames[*c].build_string(frames, depth + 1, q, str));
}
pub fn show(&self, ui: &mut Ui, q: f32, frames: &Vec<Frame>)
{
let id = ui.make_persistent_id(self.name);
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true)
.show_header(ui, |ui| {
ui.horizontal(|ui| {
ui.label(self.name);
// Right-aligned label, laid out first from the right edge
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(format!("{:.2}ms", self.time(q)));
// Whatever space remains between the two labels:
// draw a thin line across it, vertically centered.
let rect = ui.available_rect_before_wrap();
let y = rect.center().y;
ui.painter().hline(
rect.x_range(),
y,
ui.visuals().widgets.noninteractive.bg_stroke,
);
});
});
})
.body(|ui| {
self.children
.iter()
.for_each(|i| frames[*i].show(ui, q, frames));
});
}
}