// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later 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; } // one frame, in ms export interface FrameSample { // since the frame before started interval: number; // the javascript part frame: 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(); 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 }; // every frame, while something reads them, like the benchmark samples: FrameSample[] | undefined; #window_start = performance.now(); #frames = 0; #frame_start = 0; #last_frame_start = 0; #interval = 0; #sums = new Map(); #maxes = new Map(); // this frame's time per section, added to the sums when it ends #this_frame = new Map(); begin_frame() { const now = performance.now(); if (this.#last_frame_start > 0) { this.#interval = now - this.#last_frame_start; this.#add("interval", this.#interval); } this.#last_frame_start = this.#frame_start = now; this.#this_frame.clear(); } end_frame() { const now = performance.now(); const frame = now - this.#frame_start; this.#add("frame", frame); this.samples?.push({ interval: this.#interval, frame }); 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(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();