Skip to content

Core.Utilities.FrameTimer

Dennis Steffen edited this page Jan 4, 2026 · 1 revision

The FrameTimer is a high-precision performance profiling utility designed to measure and analyze frame execution times. It is particularly useful for identifying "micro-stuttering" in games or real-time applications by calculating percentiles rather than just simple averages.

Key Features

  • High-Precision Measurement: Uses Stopwatch.GetTimestamp() to provide microsecond-level accuracy, which is more reliable than standard DateTime or Environment.TickCount.
  • Percentile Analysis (P95 & P99): In addition to the average, it calculates the 95th and 99th percentiles. These represent the slowest 5% and 1% of frames, helping developers identify occasional lag spikes that ruin the user experience.
  • Multiple Units: Automatically calculates values in Microseconds (µs), Milliseconds (ms), and Frames Per Second (FPS).
  • Rolling Buffer: Stores a fixed number of recent samples (default 600) to provide a "sliding window" of current performance.

Usage

The class uses a "Scoped" pattern. You wrap the code you want to measure in a block. When the block finishes, the timer automatically records the time and updates the statistics. using

// Initialize the timer (e.g., in your game's initialization)
var frameTimer = new FrameTimer(600);

// In your main loop:
using (frameTimer.Scope())
{
    // The code you want to measure goes here
    UpdatePhysics();
    RenderFrame();
}

// Access statistics:
Console.WriteLine(frameTimer.ToString());
// Example Output: Avg: 16.67 µs (60 FPS) | p95: 20.00 µs (50 FPS) | p99: 33.33 µs (30 FPS)

Metrics Explained

  • Avg (Average): The typical time a frame takes.
  • P95 (95th Percentile): 95% of frames are faster than this value. If this is much higher than the average, the game has frequent small stutters.
  • P99 (99th Percentile): 99% of frames are faster than this value. This represents the "worst-case" performance and helps identify heavy, infrequent spikes (like garbage collection or loading resources).

Formatting Options

The class provides two built-in string formatters:

  1. ToString(): Provides a detailed breakdown in microseconds and FPS for all three metrics.
  2. ToCompactString(): Provides a simplified view using milliseconds, which is often easier to read for standard UI overlays.

Clone this wiki locally