Files
bworld/client/profiler.ts
T
2026-10-02 21:21:19 -03:00

77 lines
2.5 KiB
TypeScript

import { gpu_section } from "./renderer/mod.ts";
// how long the numbers are averaged over, so they hold still long enough to read
const WINDOW_MS = 1000;
export interface SectionStats {
// per frame, over the last window
avg: number;
max: number;
}
// what the client spends its time on, for the f3 performance window. each section is timed on the cpu, and on the gpu
// too when the renderer can, see gpu_section
class Profiler {
// what the last window came to, in ms
cpu = new Map<string, SectionStats>();
frame: SectionStats = { avg: 0, max: 0 };
// the time between frames, which is what the player feels, and the javascript part of it
interval: SectionStats & { fps: number } = { avg: 0, max: 0, fps: 0 };
#window_start = performance.now();
#frames = 0;
#frame_start = 0;
#last_frame_start = 0;
#sums = new Map<string, number>();
#maxes = new Map<string, number>();
// this frame's time per section, added to the sums when it ends
#this_frame = new Map<string, number>();
begin_frame() {
const now = performance.now();
if (this.#last_frame_start > 0) this.#add("interval", now - this.#last_frame_start);
this.#last_frame_start = this.#frame_start = now;
this.#this_frame.clear();
}
end_frame() {
const now = performance.now();
this.#add("frame", now - this.#frame_start);
for (const [name, ms] of this.#this_frame) this.#add(`cpu:${name}`, ms);
this.#frames += 1;
if (now - this.#window_start >= WINDOW_MS) this.#publish(now);
}
// runs fn as a named part of the frame. the gpu work it records is timed under the same name
section<T>(name: string, fn: () => T): T {
gpu_section(name);
const start = performance.now();
try {
return fn();
} finally {
this.#this_frame.set(name, (this.#this_frame.get(name) ?? 0) + performance.now() - start);
}
}
#add(key: string, ms: number) {
this.#sums.set(key, (this.#sums.get(key) ?? 0) + ms);
this.#maxes.set(key, Math.max(this.#maxes.get(key) ?? 0, ms));
}
#publish(now: number) {
const frames = Math.max(1, this.#frames);
const stats = (key: string) => ({ avg: (this.#sums.get(key) ?? 0) / frames, max: this.#maxes.get(key) ?? 0 });
this.frame = stats("frame");
this.interval = { ...stats("interval"), fps: this.#frames * 1000 / (now - this.#window_start) };
this.cpu = new Map(
[...this.#sums.keys()].filter((key) => key.startsWith("cpu:")).map((key) => [key.slice(4), stats(key)]),
);
this.#sums.clear();
this.#maxes.clear();
this.#frames = 0;
this.#window_start = now;
}
}
export const profiler = new Profiler();