Stats: percentile and window maths, a collector, the overlay's cells and a session summary (not wired in yet)

This commit is contained in:
alex committed 2026-11-26 04:09:21 +00:00
1 parent 7b3c42aa6d
commit ed9b4564bd
3 files changed
+1127

No files matched your search

+8
View File
@@ -34,6 +34,14 @@ def config_dir() -> Path:
return Path(os.environ.get("APPDATA", Path.home())) / "framegen"
def data_dir() -> Path:
"""Things the user keeps (session summaries, benchmark results). Windows: the same folder as the settings. Linux:
$XDG_DATA_HOME/smoovplay (~/.local/share/smoovplay)."""
if LINUX:
return _xdg("XDG_DATA_HOME", ".local/share") / "smoovplay"
return config_dir()
def cache_dir() -> Path:
"""Things that can be made again (instant replay's working files). Windows: the same folder as the settings, as
before. Linux: $XDG_CACHE_HOME/smoovplay."""
+812
View File
@@ -0,0 +1,812 @@
"""The numbers behind Summit's stats overlay and its session summaries: gathered cheaply while frames are shown,
worked out over rolling windows, formatted for the overlay (framegen/hud.py) and written when a session ends.
Nothing here needs a GPU, a window or torch: the pipeline (framegen/pipeline.py) and the window (framegen/io.py) call
`Collector` as frames are presented and as each stage finishes, so the maths can be tested with made-up times.
What is measured, and how (the README's "Stats overlay" and the overlay's help say the same):
* frametime: the time between two frames on screen (as the pipeline presents them). A gap over PAUSE_S is a pause
(a restart, a stall of the source), not a frametime: it's counted as a stall and left out of every average and low.
* fps: frames presented in the last second. 1% low / 0.1% low: the frame rate of the slowest 1% / 0.1% of frames in
the window (1000 / the mean of their frametimes: the way CapFrameX reports it). They need 100 / 1000 frames in the
window to mean anything, and show "--" until then.
* jitter: the mean change in frametime from one frame to the next (0 for perfectly even pacing).
* generated share: the share of presented frames that were generated rather than the game's own.
* dropped: generated frames left out because the pipeline was behind. repeated: frames that showed the previous
picture again because the next one hadn't arrived. late: frames presented more than 1.5 frametimes after the
one before (a stutter you could see).
* stages, in ms: capture (how long a frame waited before Summit started on it), interpolation (the AI frame, with
the graphics card waited for), upscaler and look (graphics card time, from timer queries), present (upload, swap and,
with vsync, waiting for the screen: so it reads high with vsync on).
* delay: from a real frame reaching Summit to it reaching the screen (median and 95th percentile). Everything before
Summit (the console, a capture card) and after it (the display) is left out.
* Graphics card, memory, temperature, power: nvidia-smi, read once a second on a thread of its own. CPU load: /proc/stat
(or psutil) once a second.
"""
from __future__ import annotations
import collections
import datetime as _dt
import json
import math
import os
import threading
import time
from array import array
from dataclasses import dataclass
from pathlib import Path
import numpy as np
PAUSE_S = 2.0 # a gap this long between two frames is a pause, not a frametime
LATE_FACTOR = 1.5 # a frame is late when it comes this many target frametimes after the one before
MIN_FOR_1PCT, MIN_FOR_01PCT = 100, 1000 # frames a window needs before its 1% / 0.1% low means anything
AFTER_S, SKIP_S = 6.0, 1.0 # a settings change: numbers over the next AFTER_S seconds, after SKIP_S of settling
BEFORE_S = 6.0
STAGES = ("capture", "interp", "upscale", "look", "present")
STAGE_NAMES = {"capture": "Capture wait", "interp": "AI frame", "upscale": "Upscaler", "look": "Look",
"present": "Present"}
STAGE_HELP = {"capture": "how long a frame waited before Summit started on it",
"interp": "the AI's time for one generated frame, graphics card waited for",
"upscale": "graphics card time to scale the picture",
"look": "graphics card time for the colour look",
"present": "upload and swap; with vsync on it includes waiting for the screen"}
# Settings whose changes aren't about performance: left out of a summary's list of changes
QUIET_SETTINGS = ("overlay", "overlay_", "graph_", "stat_", "stats_", "ui_", "watermark", "bar_", "session_",
"frametime_log", "replay", "look_clips")
# ---- the maths ------------------------------------------------------------------------------------------------
def low_fps(ms, fraction: float, minimum: int = 1) -> float | None:
"""The frame rate of the slowest `fraction` of the frames (their frametimes in ms): 1000 over the mean of the
worst ceil(fraction x n) of them. None with fewer than `minimum` frames."""
v = np.asarray(ms, dtype=np.float64)
n = v.size
if n == 0 or n < minimum:
return None
k = max(1, math.ceil(fraction * n))
worst = np.partition(v, n - k)[n - k:]
m = float(worst.mean())
return 1000.0 / m if m > 0 else None
def lows(ms) -> tuple[float | None, float | None]:
"""(1% low, 0.1% low) in fps, None where there are too few frames."""
return low_fps(ms, 0.01, MIN_FOR_1PCT), low_fps(ms, 0.001, MIN_FOR_01PCT)
def jitter_ms(ms) -> float | None:
"""The mean absolute change of frametime between consecutive frames."""
v = np.asarray(ms, dtype=np.float64)
return float(np.abs(np.diff(v)).mean()) if v.size >= 2 else None
def percentile(values, q: float) -> float | None:
v = np.asarray(values, dtype=np.float64)
return float(np.percentile(v, q)) if v.size else None
class Window:
"""Samples (time, value) from the last `seconds`, oldest first."""
def __init__(self, seconds: float) -> None:
self.seconds = seconds
self._t: collections.deque = collections.deque()
self._v: collections.deque = collections.deque()
def add(self, t: float, v: float) -> None:
self._t.append(t)
self._v.append(v)
self.trim(t)
def trim(self, now: float) -> None:
cut = now - self.seconds
while self._t and self._t[0] < cut:
self._t.popleft()
self._v.popleft()
def values(self, now: float | None = None) -> np.ndarray:
if now is not None:
self.trim(now)
return np.fromiter(self._v, np.float64, len(self._v))
def times(self) -> list:
return list(self._t)
def __len__(self) -> int:
return len(self._t)
def window_fps(times, now: float, span: float = 1.0) -> float | None:
"""Frames per second from presentation times, over the last `span` seconds."""
recent = [t for t in times if t > now - span]
if len(recent) < 2 or recent[-1] <= recent[0]:
return None
return (len(recent) - 1) / (recent[-1] - recent[0])
# ---- the system (CPU, graphics card) -----------------------------------------------------------------------------
class SystemSampler:
"""CPU load, the graphics card and memory, once a second on a thread of its own (the video loop never waits for
it; nothing is read per frame). Anything it can't read is None."""
def __init__(self, gpu: bool = True) -> None:
self.latest: dict = {}
self.history: list[dict] = [] # one entry a second, for the session summary (capped)
self._stop = threading.Event()
self._gpu = None
self._want_gpu = gpu
self._prev = None
self._thread = threading.Thread(target=self._run, name="sysstats", daemon=True)
def start(self) -> "SystemSampler":
if self._want_gpu:
try:
from .gpustats import GpuStats
self._gpu = GpuStats()
except Exception: # noqa: BLE001 - no GPU numbers
self._gpu = None
self._thread.start()
return self
@staticmethod
def parse_stat(text: str) -> tuple[int, int] | None:
"""(busy, total) jiffies from the first line of /proc/stat."""
try:
f = [int(x) for x in text.splitlines()[0].split()[1:9]]
except (ValueError, IndexError):
return None
if len(f) < 5:
return None
idle = f[3] + f[4] # idle + iowait
return sum(f) - idle, sum(f)
def _cpu(self) -> float | None:
try:
if os.path.exists("/proc/stat"):
cur = self.parse_stat(Path("/proc/stat").read_text())
else:
import psutil # optional: Windows and macOS
return float(psutil.cpu_percent(None))
except Exception: # noqa: BLE001
return None
if cur is None:
return None
prev, self._prev = self._prev, cur
if prev is None or cur[1] <= prev[1]:
return None
return 100.0 * (cur[0] - prev[0]) / (cur[1] - prev[1])
@staticmethod
def _memory() -> dict:
"""RAM and swap used, and this process's resident memory, in GB (Linux; else missing)."""
out: dict = {}
try:
mem = {}
for line in Path("/proc/meminfo").read_text().splitlines():
k, _, v = line.partition(":")
mem[k] = int(v.split()[0]) / 1048576.0 # kB -> GB
out["ram"] = mem["MemTotal"] - mem["MemAvailable"]
out["swap"] = mem.get("SwapTotal", 0.0) - mem.get("SwapFree", 0.0)
for line in Path("/proc/self/status").read_text().splitlines():
if line.startswith("VmRSS:"):
out["rss"] = int(line.split()[1]) / 1048576.0
except (OSError, KeyError, ValueError):
pass
return out
def sample(self) -> dict:
s = {"t": time.time(), "cpu": self._cpu(), **self._memory(), "gpu": dict(self._gpu.latest) if self._gpu and self._gpu.latest else None}
self.latest = s
if len(self.history) < 6 * 3600:
self.history.append(s)
return s
def _run(self) -> None:
while not self._stop.wait(1.0):
self.sample()
def close(self) -> None:
self._stop.set()
if self._gpu is not None:
self._gpu.close()
# ---- the collector ---------------------------------------------------------------------------------------------------
class Collector:
"""One for a whole run of the engine (it outlives restarts of the pipeline). Cheap: a few appends per frame, and
it measures its own cost (`cost`)."""
def __init__(self, window_s: float = 30.0, sampler: SystemSampler | None = None, wall=time.time) -> None:
self.window_s = window_s
self.sampler = sampler
self._wall = wall
self.started_wall = wall()
self.target_ms = 1000.0 / 60.0
self.hz = 60
self.config: dict = {}
self._last: float | None = None
self._first: float | None = None
self.ft = Window(window_s)
self.gen = Window(window_s) # 1 for a generated frame, 0 for a real one
self.late = Window(window_s)
self.dropped = Window(window_s)
self.repeated = Window(window_s)
self._recent: collections.deque = collections.deque() # presentation times of the last second
self.stage_win = {s: Window(window_s) for s in STAGES}
self.stage_all = {s: array("f") for s in STAGES}
self.frames = self.generated = self.late_total = self.dropped_total = self.repeated_total = self.stalls = 0
self.real_input = self.ticks_input = 0
self.t_all, self.ms_all = array("d"), array("f") # every counted frametime of the session
self._stats: list = [] # the pipelines' Stats, for the delay lists
self.changes: list[dict] = []
self.csv: CsvLog | None = None
self.benchmark: dict | None = None # {"seconds": N, "start": t or None}
self.cost_ns = 0 # time spent in present()
self.snap_ms = 0.0 # last snapshot's cost
self.snaps = 0
self.snap_ms_sum = 0.0
self.notes: list[str] = []
# -- configuration -----------------------------------------------------------------------------------------
def set_window(self, seconds: float) -> None:
self.window_s = seconds
for w in (self.ft, self.gen, self.late, self.dropped, self.repeated, *self.stage_win.values()):
w.seconds = seconds
def set_target(self, hz: float) -> None:
self.hz = hz
self.target_ms = 1000.0 / max(1.0, hz)
def set_config(self, **kw) -> None:
self.config.update({k: v for k, v in kw.items() if v is not None})
def attach(self, stats) -> None:
"""A pipeline's Stats (its real_delay_ms list is read for the delay numbers)."""
if stats not in self._stats:
self._stats.append(stats)
# -- events --------------------------------------------------------------------------------------------------
def present(self, t: float, generated: bool) -> None:
"""A frame went on screen at time t (perf_counter)."""
c0 = time.perf_counter_ns()
last, self._last = self._last, t
self.frames += 1
self.generated += generated
if self._first is None:
self._first = t
self.gen.add(t, 1.0 if generated else 0.0)
rec = self._recent
rec.append(t)
while rec and rec[0] <= t - 1.0:
rec.popleft()
if last is not None:
dt = t - last
if dt > PAUSE_S or dt <= 0:
self.stalls += dt > PAUSE_S
else:
ms = dt * 1000.0
self.ft.add(t, ms)
self.t_all.append(t)
self.ms_all.append(ms)
if ms > LATE_FACTOR * self.target_ms:
self.late.add(t, 1.0)
self.late_total += 1
if self.csv is not None:
self.csv.row(t, ms, generated, self)
self.cost_ns += time.perf_counter_ns() - c0
def stage(self, name: str, ms: float, t: float | None = None) -> None:
if name in self.stage_win:
self.stage_win[name].add(time.perf_counter() if t is None else t, ms)
self.stage_all[name].append(ms)
def drop(self, n: int, t: float) -> None:
if n > 0:
self.dropped.add(t, n)
self.dropped_total += n
def repeat(self, n: int, t: float) -> None:
if n > 0:
self.repeated.add(t, n)
self.repeated_total += n
def tick(self, is_new: bool | None) -> None:
self.ticks_input += 1
self.real_input += bool(is_new)
def setting_changed(self, key: str, label: str, old: str, new: str, now: float | None = None) -> None:
"""A setting changed during the session: remembered with the numbers from just before it (the after-numbers
are worked out later, once there are some)."""
if any(key.startswith(p) for p in QUIET_SETTINGS) or old == new:
return
now = time.perf_counter() if now is None else now
prev = self.changes[-1] if self.changes else None
if prev is not None and prev["key"] == key and now - prev["_t"] < 1.5: # a slider being dragged
prev["to"], prev["_t"], prev["after"] = new, now, None
return
first = now if self._first is None else self._first
before = self._span(max(first, now - BEFORE_S), now)
self.changes.append({"key": key, "label": label, "from": old, "to": new, "_t": now, "before": before,
"after": None, "at_s": round(now - first, 1)})
# -- spans of the session (for before / after) ------------------------------------------------------------------
def _span(self, t0: float, t1: float) -> dict | None:
"""fps, frametime, 1% low and late frames over the session's frames between t0 and t1; None under 1 s."""
if t1 - t0 < 1.0 or not self.t_all:
return None
t = np.array(self.t_all, np.float64)
ms = np.array(self.ms_all, np.float32)
i, j = np.searchsorted(t, t0), np.searchsorted(t, t1, side="right")
v = ms[i:j].astype(np.float64)
if v.size < 10:
return None
return {"fps": round(1000.0 / float(v.mean()), 1), "frametime_ms": round(float(v.mean()), 2),
"low1_fps": _r(low_fps(v, 0.01, MIN_FOR_1PCT)), "worst_ms": round(float(v.max()), 1),
"late": int((v > LATE_FACTOR * self.target_ms).sum()), "frames": int(v.size)}
def poll(self, now: float | None = None, final: bool = False) -> None:
"""Works out the after-numbers of settings changes whose time has come (or, `final`, whatever there is)."""
now = time.perf_counter() if now is None else now
for k, ch in enumerate(self.changes):
if ch["after"] is not None:
continue
nxt = self.changes[k + 1]["_t"] if k + 1 < len(self.changes) else None
t0, t1 = ch["_t"] + SKIP_S, ch["_t"] + SKIP_S + AFTER_S
if nxt is not None:
t1 = min(t1, nxt)
elif now < t1 and not final:
continue
ch["after"] = self._span(t0, min(t1, now)) or {}
# -- numbers for the overlay -----------------------------------------------------------------------------------
def delays(self, last: int | None = None) -> np.ndarray:
parts = [np.asarray(st.real_delay_ms if last is None else st.real_delay_ms[-last:], np.float64)
for st in self._stats]
return np.concatenate(parts) if parts else np.zeros(0)
def snapshot(self, now: float | None = None, game_fps: float | None = None) -> dict:
"""Every number the overlay can show, as plain values (None where not known yet)."""
c0 = time.perf_counter()
now = (self._last if self._last is not None else c0) if now is None else now
ft = self.ft.values(now)
low1, low01 = lows(ft)
gen = self.gen.values(now)
stages = {}
for name, w in self.stage_win.items():
v = w.values(now)
if v.size:
stages[name] = {"avg": float(v.mean()), "worst": float(v.max()), "n": int(v.size)}
d = self.delays(240)
late = len(self.late.values(now))
sysd = self.sampler.latest if self.sampler is not None else {}
snap = {
"fps": window_fps(self._recent, self._last if self._last is not None else now),
"game_fps": game_fps,
"share": float(gen.mean() * 100.0) if gen.size else None,
"ft_avg": float(ft.mean()) if ft.size else None,
"low1": low1, "low01": low01,
"ft_worst": float(ft.max()) if ft.size else None,
"jitter": jitter_ms(ft),
"frames_window": int(ft.size),
"dropped": int(self.dropped.values(now).sum()), "repeated": int(self.repeated.values(now).sum()),
"late": late,
"stages": stages,
"delay": float(np.median(d)) if d.size else None,
"delay_p95": percentile(d, 95),
"gpu": sysd.get("gpu"), "cpu": sysd.get("cpu"),
"config": dict(self.config), "hz": self.hz, "target_ms": self.target_ms,
"cost_us": self.cost_ns / max(1, self.frames) / 1000.0,
"snap_ms": self.snap_ms, "window_s": self.window_s,
}
self.snap_ms = (time.perf_counter() - c0) * 1000.0
self.snaps += 1
self.snap_ms_sum += self.snap_ms
return snap
# -- the session summary ------------------------------------------------------------------------------------------
def summary(self, now: float | None = None, reason: str = "stop", settings: dict | None = None) -> dict:
"""The whole session so far, as plain JSON-able values."""
self.poll(now, final=True)
ms = np.array(self.ms_all, np.float64)
t = np.array(self.t_all, np.float64)
span = float(t[-1] - self._first) if len(t) and self._first is not None else 0.0
low1, low01 = lows(ms)
stages = {}
for name in STAGES:
v = np.array(self.stage_all[name], np.float64)
if v.size:
stages[name] = {"avg_ms": round(float(v.mean()), 3), "p95_ms": round(float(np.percentile(v, 95)), 3),
"worst_ms": round(float(v.max()), 3), "n": int(v.size)}
d = self.delays()
sysd = _system_summary(self.sampler.history if self.sampler is not None else [])
wall_end = self._wall()
out = {
"format": 1,
"started": _dt.datetime.fromtimestamp(self.started_wall).isoformat(timespec="seconds"),
"ended": _dt.datetime.fromtimestamp(wall_end).isoformat(timespec="seconds"),
"reason": reason,
"duration_s": round(span, 2),
"benchmark": ({"seconds": self.benchmark["seconds"]} if self.benchmark else None),
"config": {**{k: v for k, v in self.config.items()}, "settings": settings or {}},
"frames": {"presented": self.frames, "generated": self.generated,
"real": self.frames - self.generated,
"generated_share_pct": _r(100.0 * self.generated / self.frames if self.frames else None, 1),
"dropped": self.dropped_total, "repeated": self.repeated_total, "late": self.late_total,
"stalls": self.stalls, "game_frames": self.real_input,
"game_fps_avg": _r(self.real_input / (self.ticks_input / 60.0), 1) if self.ticks_input else None},
"fps_avg": _r(1000.0 / float(ms.mean()), 1) if ms.size else None,
"frametime": {"avg_ms": _r(float(ms.mean()), 2) if ms.size else None,
"p99_ms": _r(percentile(ms, 99), 2), "worst_ms": _r(float(ms.max()), 1) if ms.size else None,
"low1_fps": _r(low1, 1), "low01_fps": _r(low01, 1), "jitter_ms": _r(jitter_ms(ms), 2)},
"stages": stages,
"delay": ({"median_ms": _r(float(np.median(d)), 1), "p95_ms": _r(percentile(d, 95), 1),
"max_ms": _r(float(d.max()), 1), "n": int(d.size)} if d.size else None),
"system": sysd,
"changes": [{k: v for k, v in ch.items() if not k.startswith("_")} for ch in self.changes],
"stats_cost": {"per_frame_us": round(self.cost_ns / max(1, self.frames) / 1000.0, 2),
"per_snapshot_ms": round(self.snap_ms_sum / max(1, self.snaps), 3)},
"notes": list(self.notes),
}
return out
def _r(v, nd: int = 1):
return None if v is None else round(float(v), nd)
def _system_summary(history: list[dict]) -> dict:
def col(get):
v = [x for x in (get(h) for h in history) if x is not None]
return v
cpu = col(lambda h: h.get("cpu"))
util = col(lambda h: (h.get("gpu") or {}).get("util"))
temp = col(lambda h: (h.get("gpu") or {}).get("temp"))
power = col(lambda h: (h.get("gpu") or {}).get("power"))
mem = col(lambda h: (h.get("gpu") or {}).get("mem"))
total = col(lambda h: (h.get("gpu") or {}).get("mem_total"))
return {"cpu_avg_pct": _r(np.mean(cpu)) if cpu else None, "cpu_max_pct": _r(max(cpu)) if cpu else None,
"gpu_util_avg_pct": _r(np.mean(util)) if util else None, "gpu_util_max_pct": _r(max(util)) if util else None,
"gpu_temp_max_c": _r(max(temp)) if temp else None, "gpu_power_avg_w": _r(np.mean(power)) if power else None,
"vram_max_mb": _r(max(mem), 0) if mem else None, "vram_total_mb": _r(total[0], 0) if total else None,
"samples": len(history)}
# ---- settings in words ------------------------------------------------------------------------------------------------
def config_lines(cfg: dict) -> list[tuple[str, str]]:
"""The active configuration as (name, value) rows in words. cfg: model, multiplier, hz, game_fps, upscaler, quality,
output, source, frame_generation, look."""
rows = []
if cfg.get("model"):
rows.append(("Model", str(cfg["model"])))
if "frame_generation" in cfg:
if not cfg["frame_generation"]:
rows.append(("Frame generation", "Off"))
else:
hz = cfg.get("hz")
rows.append(("Frame generation", f"{cfg['multiplier']} ({hz} fps out)" if hz and cfg.get("multiplier")
else f"{hz} fps out" if hz else "On"))
if cfg.get("upscaler"):
q = f", {cfg['quality']}" if cfg.get("quality") else ""
rows.append(("Upscaler", f"{cfg['upscaler']}{q}"))
if cfg.get("look"):
rows.append(("Look", str(cfg["look"])))
if cfg.get("output"):
rows.append(("Output size", str(cfg["output"])))
if cfg.get("source"):
rows.append(("Source size", str(cfg["source"])))
return rows
def config_line(cfg: dict) -> str:
"""The same in one line: RIFE 4.22 lite - 2x (120 fps out) - FSR 1 - 2560x1440 from 1920x1080."""
parts = []
if cfg.get("model"):
parts.append(str(cfg["model"]))
if "frame_generation" in cfg:
parts.append("no frame generation" if not cfg["frame_generation"] else
f"{cfg['multiplier']} ({cfg['hz']} fps)" if cfg.get("multiplier") and cfg.get("hz") else "frame generation")
if cfg.get("upscaler"):
parts.append(f"{cfg['upscaler']}" + (f" {cfg['quality']}" if cfg.get("quality") else ""))
if cfg.get("output") and cfg.get("source") and cfg["output"] != cfg["source"]:
parts.append(f"{cfg['output']} from {cfg['source']}")
elif cfg.get("output") or cfg.get("source"):
parts.append(str(cfg.get("output") or cfg["source"]))
return " · ".join(parts)
# ---- what the overlay shows -----------------------------------------------------------------------------------------
@dataclass(frozen=True)
class Cell:
"""One number on the overlay. value is formatted already; hint is the widest it can be (so the slot it sits in
never changes width as digits change); level is "good", "tight", "bad" or "" (no colour)."""
key: str
name: str
value: str
unit: str = ""
level: str = ""
hint: str = ""
detail: str = "" # a longer text for a row in Detailed (e.g. "avg 5.1 ms, worst 9.2 ms")
# item key -> (label in the menu, help), in menu order
ITEMS: dict[str, tuple[str, str]] = {
"fps": ("Frames per second", "The frame rate on screen: frames shown in the last second."),
"game": ("Game's frame rate", "The game's own frame rate as Summit sees it (amber when it isn't the rate that's needed)."),
"share": ("Generated share", "The share of the frames shown that Summit generated rather than the game drew."),
"frametime": ("Frametime", "The average time between frames on screen over the averaging window, in milliseconds."),
"lows": ("1% and 0.1% lows", "The frame rate of the slowest 1% and 0.1% of frames in the window. Shown as -- until the window has 100 and 1000 frames."),
"worst": ("Worst frametime", "The longest gap between two frames in the window: the biggest stutter."),
"jitter": ("Pacing jitter", "How much the time between frames changes from one frame to the next, in milliseconds. 0 is perfectly even."),
"drops": ("Dropped, repeated, late", "Dropped: generated frames left out because the PC was behind. Repeated: the last picture shown again because the next hadn't arrived. Late: frames that came more than 1.5 frametimes after the one before."),
"stages": ("Time per stage", "Milliseconds for each stage of a frame's trip: capture wait, AI frame, upscaler, look and present. Present includes waiting for the screen when vsync is on."),
"delay": ("Delay", "How long a real frame takes from reaching Summit to reaching the screen (median). The console, a capture card and the display aren't in it."),
"gpu": ("Graphics card load", "How busy the graphics card is (nvidia-smi, once a second)."),
"vram": ("Video memory", "Graphics memory in use, of the card's total, all programs together."),
"temp": ("Graphics card temperature", "The graphics card's temperature in degrees Celsius."),
"power": ("Graphics card power", "What the graphics card draws, in watts."),
"cpu": ("CPU load", "How busy the processor is, all programs together."),
"config": ("Settings in words", "The model, the multiplier, the upscaler and its quality, and the output and source sizes."),
"cost": ("Overlay's own cost", "What gathering and drawing these numbers costs, per frame."),
}
DEFAULT_ITEMS = {
"minimal": ("fps", "game", "delay"),
"detailed": ("fps", "game", "delay", "share", "frametime", "lows", "worst", "jitter", "drops", "stages", "gpu",
"vram", "temp", "power", "cpu", "config", "cost"),
"bar": ("fps", "game", "share", "frametime", "lows", "drops", "delay", "gpu", "temp"),
}
DETAILED_OFF = ("worst", "power", "cpu", "cost") # Detailed's default list is long: these come after the rest
def default_items(style: str) -> tuple[str, ...]:
return DEFAULT_ITEMS.get(style, DEFAULT_ITEMS["minimal"])
def wanted(style: str, choice) -> list[str]:
"""The items to show: the style's own list, with each stat_<item> setting ("auto", "on", "off") applied.
choice(key) -> the setting's value. In ITEMS order, so a layout never depends on the order things were turned on."""
base = set(default_items(style))
out = []
for key in ITEMS:
c = choice(key)
if c == "on" or (c != "off" and key in base):
out.append(key)
return out
def level_of(value: float | None, good: float, tight: float, higher_is_better: bool = False) -> str:
""""good" up to `good`, "tight" up to `tight`, "bad" past it (reversed when higher is better); "" for no value."""
if value is None:
return ""
if higher_is_better:
return "good" if value >= good else "tight" if value >= tight else "bad"
return "good" if value <= good else "tight" if value <= tight else "bad"
def _f(v, nd: int = 1, dash: str = "--") -> str:
return dash if v is None else f"{v:.{nd}f}"
def cells(snap: dict, item: str, colours: bool = True, inline: bool = True, note: bool = False) -> list[Cell]:
"""The overlay's cells for one item, from a Collector.snapshot(). inline: for a line (Minimal, the bar); else for
rows (Detailed). note: the game's rate is off the rate that's needed (shown amber)."""
tgt, hz = snap["target_ms"], snap["hz"]
lv = (lambda s: s) if colours else (lambda s: "")
out: list[Cell] = []
if item == "fps":
v = snap["fps"]
out.append(Cell("fps", "", _f(v, 0), "fps", lv(level_of(v, 0.9 * hz, 0.6 * hz, True)), "888"))
elif item == "game":
v = snap["game_fps"]
if v is not None:
out.append(Cell("game", "game", _f(v, 0), "", lv("tight" if note else ""), "88"))
elif item == "share":
v = snap["share"]
out.append(Cell("share", "generated", _f(v, 0), "%", "", "888"))
elif item == "frametime":
v = snap["ft_avg"]
out.append(Cell("frametime", "frametime", _f(v), "ms", lv(level_of(v, 1.35 * tgt, 2.2 * tgt)), "888.8"))
elif item == "lows":
for k, name in (("low1", "1% low"), ("low01", "0.1% low")):
v = snap[k]
out.append(Cell(k, name, _f(v, 0), "fps", lv(level_of(v, hz / 1.35, hz / 2.2, True)), "888"))
elif item == "worst":
v = snap["ft_worst"]
out.append(Cell("worst", "worst", _f(v), "ms", lv(level_of(v, 2.2 * tgt, 4.0 * tgt)), "888.8"))
elif item == "jitter":
v = snap["jitter"]
out.append(Cell("jitter", "jitter", _f(v), "ms", lv(level_of(v, 0.25 * tgt, 0.6 * tgt)), "88.8"))
elif item == "drops":
n = max(1, snap["frames_window"])
for k, name in (("dropped", "dropped"), ("repeated", "repeated"), ("late", "late")):
v = snap[k]
out.append(Cell(k, name, f"{v:d}", "", lv("" if v == 0 else "bad" if v / n >= 0.01 else "tight"), "8888"))
elif item == "stages":
for name in STAGES:
s = snap["stages"].get(name)
if s is None:
continue
lvl = level_of(s["avg"], 0.5 * tgt, 0.9 * tgt) if name != "present" else ""
out.append(Cell("stage_" + name, STAGE_NAMES[name] if not inline else _short(name), _f(s["avg"]), "ms",
lv(lvl), "88.8", f"{_f(s['avg'], 2)} ms avg, {_f(s['worst'], 1)} ms worst"))
elif item == "delay":
v = snap["delay"]
if v is not None:
out.append(Cell("delay", "delay", _f(v, 0), "ms", lv(level_of(v, 45.0, 80.0)), "888",
f"{_f(v, 0)} ms median, {_f(snap['delay_p95'], 0)} ms p95"))
elif item in ("gpu", "vram", "temp", "power"):
g = snap["gpu"]
if g:
if item == "gpu":
out.append(Cell("gpu", "GPU", _f(g["util"], 0), "%", lv(level_of(g["util"], 85.0, 95.0)), "888"))
elif item == "vram":
used, total = g["mem"] / 1024.0, g["mem_total"] / 1024.0
out.append(Cell("vram", "VRAM", f"{used:.1f}/{total:.0f}", "GB",
lv(level_of(used / total if total else None, 0.8, 0.92)), "88.8/88"))
elif item == "temp":
out.append(Cell("temp", "GPU temp", _f(g["temp"], 0), "C", lv(level_of(g["temp"], 74.0, 84.0)), "888"))
else:
out.append(Cell("power", "power", _f(g["power"], 0), "W", "", "888"))
elif item == "cpu":
v = snap["cpu"]
if v is not None:
out.append(Cell("cpu", "CPU", _f(v, 0), "%", lv(level_of(v, 75.0, 90.0)), "888"))
elif item == "config":
if inline:
line = config_line(snap["config"])
if line:
out.append(Cell("config", "", line))
else:
out += [Cell("config", n, v) for n, v in config_lines(snap["config"])]
elif item == "cost":
out.append(Cell("cost", "overlay", f"{snap['cost_us']:.0f}", "us/frame", "", "8888",
f"{snap['cost_us']:.0f} us a frame, {snap['snap_ms']:.2f} ms a refresh"))
return out
def _short(stage: str) -> str:
return {"capture": "cap", "interp": "AI", "upscale": "up", "look": "look", "present": "pres"}[stage]
def all_cells(snap: dict, items: list[str], colours: bool, inline: bool, note: bool = False) -> list[Cell]:
return [c for it in items for c in cells(snap, it, colours, inline, note)]
# ---- writing ------------------------------------------------------------------------------------------------------------
def sessions_dir() -> Path:
from . import oslayer
return oslayer.data_dir() / "sessions"
def stamp(wall: float | None = None) -> str:
return time.strftime("%Y%m%d-%H%M%S", time.localtime(wall))
def write_summary(summary: dict, directory: Path | None = None, name: str | None = None) -> tuple[Path, Path]:
"""summit-session-<stamp>.json and .txt in `directory` (default: Summit's data folder). Returns both paths."""
d = Path(directory) if directory is not None else sessions_dir()
d.mkdir(parents=True, exist_ok=True)
base = name or f"summit-{'benchmark' if summary.get('benchmark') else 'session'}-{stamp()}"
j, t = d / f"{base}.json", d / f"{base}.txt"
j.write_text(json.dumps(summary, indent=2), encoding="utf-8")
t.write_text(format_table(summary) + "\n", encoding="utf-8")
return j, t
def _dur(s: float) -> str:
s = int(round(s))
return f"{s // 3600}:{s % 3600 // 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60}:{s % 60:02d}"
def _v(x, unit: str = "", nd: int = 1) -> str:
return "--" if x is None else f"{x:.{nd}f}{(' ' + unit) if unit else ''}"
def format_table(s: dict) -> str:
"""The summary as a plain-text table that fits one screen (under 40 lines of 78 columns)."""
cfg = s["config"]
fr, ft = s["frames"], s["frametime"]
L = []
title = f"Summit {'benchmark' if s.get('benchmark') else 'session'} summary"
L.append(title)
L.append("=" * len(title))
L.append(f"{s['started']} to {s['ended']} ({_dur(s['duration_s'])} played, ended by {s['reason']})")
if s.get("benchmark"):
L.append(f"Benchmark: {s['benchmark']['seconds']} s")
line = config_line(cfg)
if line:
L.append(f"Setup: {line}")
L.append("")
L.append(f"{'Frames per second':<26}{_v(s['fps_avg'], 'fps'):>12} game {_v(fr['game_fps_avg'], 'fps', 0)}, "
f"{_v(fr['generated_share_pct'], '%', 0)} generated")
L.append(f"{'Frametime avg / worst':<26}{_v(ft['avg_ms'], 'ms'):>12} worst {_v(ft['worst_ms'], 'ms')}")
L.append(f"{'1% low / 0.1% low':<26}{_v(ft['low1_fps'], 'fps', 0):>12} 0.1% low {_v(ft['low01_fps'], 'fps', 0)}")
L.append(f"{'Pacing jitter':<26}{_v(ft['jitter_ms'], 'ms', 2):>12}")
L.append(f"{'Dropped / repeated / late':<26}{fr['dropped']:>12} {fr['repeated']} repeated, {fr['late']} late "
f"({fr['presented']} frames shown, {fr['stalls']} stalls)")
d = s.get("delay")
L.append(f"{'Delay median / p95':<26}{_v(d and d['median_ms'], 'ms', 0):>12} p95 {_v(d and d['p95_ms'], 'ms', 0)}, "
f"max {_v(d and d['max_ms'], 'ms', 0)}")
L.append("")
if s["stages"]:
L.append(f"{'Stage':<26}{'avg ms':>8}{'p95 ms':>9}{'worst ms':>10}")
for name in STAGES:
st = s["stages"].get(name)
if st:
L.append(f"{STAGE_NAMES[name]:<26}{st['avg_ms']:>8.2f}{st['p95_ms']:>9.2f}{st['worst_ms']:>10.2f}")
L.append("")
sy = s["system"]
L.append(f"{'System':<26}GPU {_v(sy['gpu_util_avg_pct'], '%', 0)} avg ({_v(sy['gpu_util_max_pct'], '%', 0)} max), "
f"VRAM {_v(sy['vram_max_mb'] and sy['vram_max_mb'] / 1024, 'GB')} of {_v(sy['vram_total_mb'] and sy['vram_total_mb'] / 1024, 'GB', 0)}")
L.append(f"{'':<26}GPU temp {_v(sy['gpu_temp_max_c'], 'C', 0)} max, power {_v(sy['gpu_power_avg_w'], 'W', 0)} avg, "
f"CPU {_v(sy['cpu_avg_pct'], '%', 0)} avg")
if s["changes"]:
L.append("")
L.append("Settings changed during the session (fps and 1% low just before -> a second after it settled):")
for ch in s["changes"][:8]:
b, a = ch.get("before") or {}, ch.get("after") or {}
nums = (f"{_v(b.get('fps'), '', 0)} -> {_v(a.get('fps'), '', 0)} fps, 1% low "
f"{_v(b.get('low1_fps'), '', 0)} -> {_v(a.get('low1_fps'), '', 0)}")
L.append(f" at {_dur(ch['at_s'])} {ch['label']}: {ch['from']} -> {ch['to']} {nums}")
if len(s["changes"]) > 8:
L.append(f" ... and {len(s['changes']) - 8} more (in the JSON)")
sc = s["stats_cost"]
L.append("")
L.append(f"The stats cost {sc['per_frame_us']:.0f} us per frame and {sc['per_snapshot_ms']:.2f} ms per overlay refresh.")
for n in s["notes"]:
L.append(n)
return "\n".join(L)
# ---- the CSV frametime log -----------------------------------------------------------------------------------------------
MANGOHUD_COLUMNS = ("fps", "frametime", "cpu_load", "gpu_load", "cpu_temp", "gpu_temp", "gpu_core_clock",
"gpu_mem_clock", "gpu_vram_used", "gpu_power", "ram", "swap", "process_rss", "elapsed")
class CsvLog:
"""A row per frame on screen: MangoHud's log columns (fps, frametime in ms, loads, temperatures, clocks, memory in GB,
power, elapsed in ns), then `generated` (1 for a frame Summit generated). Columns Summit can't read are 0, as in
MangoHud's. The two lines before the header (system and values) are MangoHud's too. Buffered; closed with close()."""
def __init__(self, path, info: dict | None = None) -> None:
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self._f = open(self.path, "w", encoding="utf-8", newline="\n", buffering=1 << 16)
info = info or {}
keys = ("os", "cpu", "gpu", "ram", "kernel", "driver", "cpuscheduler")
self._f.write(",".join(keys) + "\n" + ",".join(str(info.get(k, "")).replace(",", " ") for k in keys) + "\n")
self._f.write(",".join(MANGOHUD_COLUMNS) + ",generated\n")
self._t0: float | None = None
self.rows = 0
def row(self, t: float, ms: float, generated: bool, c: "Collector") -> None:
self._t0 = t - ms / 1000.0 if self._t0 is None else self._t0
s = c.sampler.latest if c.sampler is not None else {}
g = s.get("gpu") or {}
self._f.write(f"{1000.0 / ms:.1f},{ms:.3f},{s.get('cpu') or 0:.0f},{g.get('util', 0):.0f},0,{g.get('temp', 0):.0f},"
f"{g.get('clock', 0):.0f},0,{g.get('mem', 0) / 1024:.2f},{g.get('power', 0):.1f},{s.get('ram', 0):.2f},"
f"{s.get('swap', 0):.2f},{s.get('rss', 0):.2f},{int((t - self._t0) * 1e9)},{int(generated)}\n")
self.rows += 1
def close(self) -> None:
try:
self._f.close()
except OSError:
pass
def system_info() -> dict:
"""The first line of a CSV log: os, cpu, gpu, ram (GB), kernel, driver, scheduler. Whatever can be read."""
import platform
info = {"os": platform.system(), "kernel": platform.release()}
try:
for line in Path("/proc/cpuinfo").read_text().splitlines():
if line.startswith("model name"):
info["cpu"] = line.split(":", 1)[1].strip()
break
mem = Path("/proc/meminfo").read_text().splitlines()[0]
info["ram"] = f"{int(mem.split()[1]) / 1048576.0:.0f}"
except (OSError, ValueError, IndexError):
pass
return info
+307
View File
@@ -0,0 +1,307 @@
"""Summit's statistics (framegen/stats.py): the percentile and window maths, the collector, the overlay's cells and the
session summary. Everything runs on made-up frame times: no GPU, no window."""
import json
import pathlib
import sys
import types
import numpy as np
import pytest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from framegen import stats as S
def feed(c: S.Collector, ms_list, t0: float = 100.0, gen_every: int = 2):
"""Presents frames `ms` apart; every `gen_every`th is generated."""
t = t0
c.present(t, False)
for i, ms in enumerate(ms_list, 1):
t += ms / 1000.0
c.present(t, i % gen_every == 0)
return t
# ---- the maths ----------------------------------------------------------------------------------------------------
def test_low_fps_is_the_mean_of_the_worst_frames():
ms = [10.0] * 98 + [50.0, 30.0] # 100 frames: the worst 1% is one frame (50 ms)
assert S.low_fps(ms, 0.01) == pytest.approx(1000 / 50)
assert S.low_fps(ms, 0.02) == pytest.approx(1000 / 40) # worst 2: 50 and 30 -> mean 40
assert S.low_fps(ms, 0.05) == pytest.approx(1000 / ((50 + 30 + 3 * 10) / 5))
assert S.low_fps([16.0, 17.0], 0.5) == pytest.approx(1000 / 17) # at least one frame, rounded up
assert S.low_fps([], 0.01) is None
def test_lows_need_enough_frames():
assert S.lows([10.0] * 99) == (None, None)
one, tenth = S.lows([10.0] * 100)
assert one == pytest.approx(100.0) and tenth is None
ms = np.full(1000, 8.0)
ms[0] = 80.0
one, tenth = S.lows(ms)
assert tenth == pytest.approx(1000 / 80) # the worst 0.1% of 1000 is one frame
assert one == pytest.approx(1000 / ((80 + 9 * 8) / 10)) # the worst 1%: ten frames
def test_percentile_matches_numpy_and_jitter_is_mean_step():
v = list(range(1, 101))
assert S.percentile(v, 95) == pytest.approx(np.percentile(v, 95))
assert S.percentile([], 95) is None
assert S.jitter_ms([10, 10, 10]) == 0.0
assert S.jitter_ms([10, 14, 10, 14]) == pytest.approx(4.0)
assert S.jitter_ms([10]) is None
def test_window_drops_what_is_older_than_its_span():
w = S.Window(5.0)
for t in range(10):
w.add(float(t), t * 2.0)
assert list(w.values()) == [8.0, 10.0, 12.0, 14.0, 16.0, 18.0] # t = 4..9: the last 5 s, ends included
assert len(w) == 6
assert list(w.values(now=20.0)) == [] # nothing left by then
assert S.window_fps([0.0, 0.1, 0.2, 0.3, 0.4], 0.4) == pytest.approx(10.0)
assert S.window_fps([0.0], 0.0) is None
# ---- the collector ----------------------------------------------------------------------------------------------------
def test_fps_frametime_and_share_from_even_frames():
c = S.Collector(window_s=30)
c.set_target(120)
t = feed(c, [1000 / 120] * 240)
snap = c.snapshot(t)
assert snap["fps"] == pytest.approx(120.0, abs=0.5)
assert snap["ft_avg"] == pytest.approx(1000 / 120, rel=1e-3)
assert snap["jitter"] == pytest.approx(0.0, abs=1e-3)
assert snap["share"] == pytest.approx(50.0, abs=1)
assert snap["late"] == 0 and snap["frames_window"] == 240
assert snap["low1"] == pytest.approx(120.0, rel=1e-3) and snap["low01"] is None # 240 frames: no 0.1% low yet
def test_a_stutter_shows_in_the_lows_worst_jitter_and_late_count():
c = S.Collector()
c.set_target(60)
ms = [16.667] * 199 + [100.0]
t = feed(c, ms)
snap = c.snapshot(t)
assert snap["ft_worst"] == pytest.approx(100.0)
assert snap["late"] == 1 # only the 100 ms frame is more than 1.5 targets
assert snap["low1"] == pytest.approx(1000 / ((100 + 1 * 16.667) / 2), rel=1e-3) # worst 1% of 200 = 2 frames
assert snap["jitter"] == pytest.approx((100 - 16.667) / 199, rel=1e-3) # one step up, at the end
def test_a_long_gap_is_a_pause_not_a_frametime():
c = S.Collector()
c.present(0.0, False)
c.present(0.016, False)
c.present(5.0, False) # a restart, say
c.present(5.016, False)
assert c.stalls == 1 and len(c.t_all) == 2
assert c.snapshot(5.016)["ft_worst"] == pytest.approx(16.0)
def test_the_window_forgets_old_frames():
c = S.Collector(window_s=5.0)
feed(c, [50.0] * 100, t0=0.0) # five seconds of 20 fps
t = feed(c, [10.0] * 600, t0=5.5) # then six of 100 fps
snap = c.snapshot(t)
assert snap["ft_avg"] == pytest.approx(10.0, abs=0.2) and snap["ft_worst"] < 20
assert snap["fps"] == pytest.approx(100.0, abs=1)
def test_dropped_repeated_and_late_are_counted_in_the_window_and_in_total():
c = S.Collector(window_s=10.0)
c.set_target(60)
c.drop(2, 1.0)
c.repeat(1, 2.0)
c.drop(1, 30.0) # (10 s window: the first two are gone by then)
snap = c.snapshot(30.0)
assert snap["dropped"] == 1 and snap["repeated"] == 0
assert c.dropped_total == 3 and c.repeated_total == 1
def test_stage_costs_average_and_worst():
c = S.Collector()
for ms in (4.0, 6.0, 5.0, 9.0):
c.stage("interp", ms, t=1.0)
c.stage("present", 0.5, t=1.0)
c.stage("nonsense", 1.0, t=1.0) # not a stage: ignored
st = c.snapshot(2.0)["stages"]
assert st["interp"]["avg"] == pytest.approx(6.0) and st["interp"]["worst"] == 9.0 and st["interp"]["n"] == 4
assert "upscale" not in st and "nonsense" not in st
def test_delay_comes_from_the_attached_stats():
c = S.Collector()
c.attach(types.SimpleNamespace(real_delay_ms=[20.0, 22.0, 40.0]))
snap = c.snapshot(1.0)
assert snap["delay"] == pytest.approx(22.0) and snap["delay_p95"] == pytest.approx(np.percentile([20, 22, 40], 95))
assert S.Collector().snapshot(1.0)["delay"] is None
def test_gathering_costs_little_and_says_how_much():
c = S.Collector()
t = feed(c, [8.3] * 2000)
snap = c.snapshot(t)
assert 0 < snap["cost_us"] < 200 # a few microseconds a frame (generous: shared CI hosts)
c.snapshot(t)
assert c.snap_ms < 50
assert c.summary()["stats_cost"]["per_frame_us"] == pytest.approx(snap["cost_us"], rel=0.5)
# ---- changes of settings --------------------------------------------------------------------------------------------
def test_a_setting_change_gets_before_and_after_numbers():
c = S.Collector()
c.set_target(60)
t = feed(c, [20.0] * 500, t0=0.0) # 10 s at 50 fps
c.setting_changed("scaler", "Upscaler", "FSR 1", "Off", now=t)
t = feed(c, [10.0] * 1000, t0=t + 0.01) # then 10 s at 100 fps
c.setting_changed("overlay_style", "Stats overlay style", "Minimal", "Bar", now=t) # not a performance setting
s = c.summary(now=t)
assert len(s["changes"]) == 1
ch = s["changes"][0]
assert (ch["key"], ch["from"], ch["to"]) == ("scaler", "FSR 1", "Off")
assert ch["before"]["fps"] == pytest.approx(50.0, abs=0.5)
assert ch["after"]["fps"] == pytest.approx(100.0, abs=1.0)
assert "_t" not in ch
def test_a_dragged_slider_is_one_change_and_a_too_early_summary_has_no_after():
c = S.Collector()
t = feed(c, [10.0] * 300, t0=0.0)
for k, v in enumerate(("1x", "2x", "3x")):
c.setting_changed("hz", "Frame multiplier", "60", v, now=t + 0.1 * k)
assert len(c.changes) == 1 and c.changes[0]["to"] == "3x" and c.changes[0]["from"] == "60"
s = c.summary(now=t + 0.5)
assert s["changes"][0]["after"] == {} # under a second of frames since: nothing to say
# ---- what the overlay shows ---------------------------------------------------------------------------------------
def snap_for(**over):
c = S.Collector()
c.set_target(120)
c.set_config(model="RIFE 4.22", multiplier="4x", hz=120, upscaler="FSR 1", output="2560x1440", source="1920x1080",
frame_generation=True)
t = feed(c, [1000 / 120] * 400)
for st, v in (("capture", 1.0), ("interp", 5.0), ("upscale", 1.2), ("look", 0.2), ("present", 0.7)):
c.stage(st, v, t=t)
c.sampler = types.SimpleNamespace(latest={"cpu": 31.0, "gpu": {"util": 83.0, "power": 210.0, "temp": 71.0, "mem": 5120.0,
"mem_total": 24576.0, "clock": 1900.0}})
c.attach(types.SimpleNamespace(real_delay_ms=[25.0] * 50))
snap = c.snapshot(t, game_fps=30.0)
snap.update(over)
return snap
def test_every_item_makes_cells_and_the_minimal_ones_match_the_old_line():
snap = snap_for()
for item in S.ITEMS:
assert S.cells(snap, item), item
mini = S.all_cells(snap, S.wanted("minimal", lambda k: "auto"), True, True)
assert [c.key for c in mini] == ["fps", "game", "delay"]
assert mini[0].value == "120" and mini[0].unit == "fps" and mini[2].value == "25"
def test_wanted_follows_the_style_and_each_stat_setting():
auto = lambda k: "auto" # noqa: E731
assert S.wanted("minimal", auto) == ["fps", "game", "delay"]
assert "lows" in S.wanted("bar", auto) and "stages" not in S.wanted("bar", auto)
assert set(S.wanted("detailed", auto)) == set(S.ITEMS)
pick = lambda k: {"temp": "on", "game": "off"}.get(k, "auto") # noqa: E731
assert S.wanted("minimal", pick) == ["fps", "delay", "temp"] # in the menu's order, whatever was turned on
def test_colours_follow_the_thresholds():
snap = snap_for()
level = lambda item: S.cells(snap, item)[0].level # noqa: E731
assert level("fps") == "good" and level("temp") == "good" and level("gpu") == "good"
snap["fps"], snap["gpu"]["temp"], snap["gpu"]["util"] = 80.0, 80.0, 99.0 # 120 target: 80 is "tight"
assert level("fps") == "tight" and level("temp") == "tight" and level("gpu") == "bad"
snap["fps"], snap["gpu"]["temp"] = 40.0, 90.0
assert level("fps") == "bad" and level("temp") == "bad"
assert S.cells(snap, "fps", colours=False)[0].level == "" # the setting that turns colours off
assert S.level_of(None, 1, 2) == ""
assert S.level_of(10, 20, 30) == "good" and S.level_of(25, 20, 30) == "tight" and S.level_of(31, 20, 30) == "bad"
assert S.level_of(50, 60, 30, True) == "tight" and S.level_of(70, 60, 30, True) == "good"
def test_unknown_numbers_show_dashes_not_zero():
snap = snap_for(fps=None, ft_avg=None, low1=None, low01=None)
assert S.cells(snap, "fps")[0].value == "--" and S.cells(snap, "frametime")[0].value == "--"
assert [c.value for c in S.cells(snap, "lows")] == ["--", "--"]
snap["gpu"] = None
assert S.cells(snap, "gpu") == [] and S.cells(snap, "vram") == []
def test_configuration_in_words():
cfg = {"model": "RIFE 4.22", "frame_generation": True, "multiplier": "4x", "hz": 120, "upscaler": "RTX VSR",
"quality": "quality 3", "output": "3840x2160", "source": "1920x1080"}
assert S.config_line(cfg) == "RIFE 4.22 · 4x (120 fps) · RTX VSR quality 3 · 3840x2160 from 1920x1080"
rows = dict(S.config_lines(cfg))
assert rows["Frame generation"] == "4x (120 fps out)" and rows["Upscaler"] == "RTX VSR, quality 3"
assert rows["Source size"] == "1920x1080"
assert dict(S.config_lines({"frame_generation": False}))["Frame generation"] == "Off"
# ---- the summary ------------------------------------------------------------------------------------------------------
def test_summary_has_the_numbers_and_a_one_screen_table(tmp_path):
c = S.Collector()
c.set_target(120)
c.set_config(model="RIFE 4.22", frame_generation=True, multiplier="4x", hz=120, upscaler="FSR 1")
c.sampler = types.SimpleNamespace(latest={}, history=[
{"cpu": 20.0, "gpu": {"util": 60.0, "power": 200.0, "temp": 65.0, "mem": 4000.0, "mem_total": 24000.0}},
{"cpu": 40.0, "gpu": {"util": 90.0, "power": 240.0, "temp": 70.0, "mem": 4400.0, "mem_total": 24000.0}}])
for _ in range(300):
c.tick(True)
c.tick(False)
c.attach(types.SimpleNamespace(real_delay_ms=[20.0, 30.0, 25.0]))
feed(c, [1000 / 120] * 600)
for ms in (4.0, 5.0, 6.0):
c.stage("interp", ms)
s = c.summary(reason="the Stop button", settings={"hz": 120})
assert s["fps_avg"] == pytest.approx(120.0, abs=0.1) and s["frames"]["presented"] == 601
assert s["frames"]["generated_share_pct"] == pytest.approx(50.0, abs=0.2)
assert s["frames"]["game_fps_avg"] == pytest.approx(30.0, abs=0.1) # 1 in 2 ticks new, 60 ticks/s
assert s["frametime"]["low1_fps"] == pytest.approx(120.0, abs=0.1) and s["frametime"]["low01_fps"] is None
assert s["stages"]["interp"]["avg_ms"] == pytest.approx(5.0) and s["stages"]["interp"]["worst_ms"] == 6.0
assert s["delay"]["median_ms"] == 25.0 and s["system"]["gpu_util_avg_pct"] == 75.0 and s["system"]["vram_max_mb"] == 4400.0
assert s["config"]["settings"] == {"hz": 120}
table = S.format_table(s)
assert len(table.splitlines()) <= 36 and max(len(x) for x in table.splitlines()) <= 120
assert "Frames per second" in table and "AI frame" in table and "120.0 fps" in table
json_path, txt_path = S.write_summary(s, tmp_path, "t")
assert json.loads(json_path.read_text())["fps_avg"] == s["fps_avg"] and txt_path.read_text().startswith("Summit session")
json.dumps(s) # all plain values
def test_an_empty_session_still_summarises():
s = S.Collector().summary()
assert s["frames"]["presented"] == 0 and s["fps_avg"] is None and s["duration_s"] == 0
assert "Summit session summary" in S.format_table(s)
# ---- the CSV log ---------------------------------------------------------------------------------------------------------
def test_csv_log_has_mangohuds_columns(tmp_path):
c = S.Collector()
c.sampler = types.SimpleNamespace(latest={"cpu": 12.0, "ram": 8.0, "swap": 0.0, "rss": 1.5, "gpu": {
"util": 50.0, "power": 100.0, "temp": 60.0, "mem": 2048.0, "mem_total": 24576.0, "clock": 1800.0}})
c.csv = S.CsvLog(tmp_path / "log.csv", {"os": "Linux", "cpu": "Some, CPU", "kernel": "7.0"})
feed(c, [10.0, 20.0, 10.0])
c.csv.close()
lines = (tmp_path / "log.csv").read_text().splitlines()
assert lines[0] == "os,cpu,gpu,ram,kernel,driver,cpuscheduler" and lines[1].startswith("Linux,Some CPU,")
assert lines[2] == ",".join(S.MANGOHUD_COLUMNS) + ",generated"
first = lines[3].split(",")
assert len(first) == len(S.MANGOHUD_COLUMNS) + 1
assert float(first[0]) == pytest.approx(100.0, abs=0.1) and float(first[1]) == pytest.approx(10.0, abs=0.01)
assert first[3] == "50" and first[8] == "2.00"
assert [float(x.split(",")[1]) for x in lines[3:]] == pytest.approx([10.0, 20.0, 10.0], abs=0.01)
elapsed = [int(x.split(",")[13]) for x in lines[3:]]
assert elapsed == sorted(elapsed) and elapsed[-1] == pytest.approx(40e6, rel=0.01) # ns since the first frame
def test_cpu_load_parses_proc_stat():
a = S.SystemSampler.parse_stat("cpu 100 0 100 800 0 0 0 0 0 0\ncpu0 1 2 3")
b = S.SystemSampler.parse_stat("cpu 200 0 200 1000 0 0 0 0 0 0\n")
assert a == (200, 1000) and b == (400, 1400)
assert 100.0 * (b[0] - a[0]) / (b[1] - a[1]) == pytest.approx(50.0)
assert S.SystemSampler.parse_stat("garbage") is None