The engine's summary now says which game it was (SUMMIT_GAME, which summit run/enhance already set) and ended_unix. The reader takes duration_s, fps_avg, the engine's low1_fps/low01_fps (as 1% / 0.1% low), its ISO "ended" for older files, and shows the config words (model, multiplier...) instead of the 80 settings. Tested against a real benchmark summary written by the engine on the GPU VM (checked in as a fixture) and stats' own older real summary.
891 lines
44 KiB
Python
891 lines
44 KiB
Python
"""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
|
|
WARMUP_MAX_S, WARMUP_CAPTURE_MS = 10.0, 100.0 # ...and until a frame no longer waits long to be started on (a backlog
|
|
# from the start-up has cleared), but no longer than WARMUP_MAX_S
|
|
WARMUP_FRAMES = 3 # the first frames shown are left out (the engine's start-up can take seconds); counting starts after
|
|
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 # framegen.gpustats.GpuStats, once started (the window's graphs share it)
|
|
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,
|
|
warmup: int = 0) -> None:
|
|
self.window_s = window_s
|
|
self.warmup, self._warm = warmup, 0 # frames left out at the start (WARMUP_FRAMES in a real run)
|
|
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, "done": bool}
|
|
self.save_hook = None # save_hook(reason) -> a line saying where the summary went (run.py sets it)
|
|
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] = []
|
|
self._delay_skip: dict = {}
|
|
self._cap_last, self._warm_t0 = 0.0, 0.0 # the last capture wait, ms; when the warm-up began
|
|
|
|
# -- 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)
|
|
|
|
# -- the benchmark -------------------------------------------------------------------------------------------
|
|
def start_benchmark(self, seconds: float) -> None:
|
|
"""A fixed-time run. The first WARMUP_FRAMES frames shown are left out of everything (the start-up of the
|
|
engine, which can take seconds), and the clock starts with the frame after them."""
|
|
self.benchmark = {"seconds": float(seconds), "start": None, "done": False}
|
|
if self._warm == 0:
|
|
self.warmup = max(self.warmup, WARMUP_FRAMES)
|
|
|
|
def bench_left(self, now: float | None = None) -> float | None:
|
|
"""Seconds of the benchmark left (all of it before the first frame), None when there isn't one."""
|
|
b = self.benchmark
|
|
if b is None:
|
|
return None
|
|
if b["start"] is None:
|
|
return b["seconds"]
|
|
now = time.perf_counter() if now is None else now
|
|
return max(0.0, b["seconds"] - (now - b["start"]))
|
|
|
|
def bench_over(self, now: float | None = None) -> bool:
|
|
"""Whether a benchmark was asked for and its time is up (it says so once, and stays over)."""
|
|
b = self.benchmark
|
|
if b is None:
|
|
return False
|
|
if not b["done"] and b["start"] is not None and self.bench_left(now) <= 0.0:
|
|
b["done"] = True
|
|
return b["done"]
|
|
|
|
# -- events --------------------------------------------------------------------------------------------------
|
|
def present(self, t: float, generated: bool) -> None:
|
|
"""A frame went on screen at time t (perf_counter)."""
|
|
c0 = time.perf_counter_ns()
|
|
if self._warm < self.warmup: # the engine's start-up (seconds, the first time): not counted
|
|
self._warm += 1
|
|
self._last = t
|
|
if self._warm == 1:
|
|
self._warm_t0 = t
|
|
if self._warm < self.warmup:
|
|
return
|
|
if self._warm == self.warmup and self._cap_last > WARMUP_CAPTURE_MS and t - self._warm_t0 < WARMUP_MAX_S:
|
|
self._warm -= 1 # still working off a backlog: keep waiting
|
|
return
|
|
self._reset(t)
|
|
b = self.benchmark
|
|
if b is not None and b["start"] is None:
|
|
b["start"] = t
|
|
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 _reset(self, t: float) -> None:
|
|
"""Forget what was gathered so far (the benchmark's warm-up). Settings and the configuration stay."""
|
|
for w in (self.ft, self.gen, self.late, self.dropped, self.repeated, *self.stage_win.values()):
|
|
w._t.clear()
|
|
w._v.clear()
|
|
self._recent.clear()
|
|
for name in STAGES:
|
|
self.stage_all[name] = array("f")
|
|
self.t_all, self.ms_all = array("d"), array("f")
|
|
self.frames = self.generated = self.late_total = self.dropped_total = self.repeated_total = self.stalls = 0
|
|
self.real_input = self.ticks_input = 0
|
|
self.cost_ns = 0
|
|
self.changes.clear()
|
|
self._first = self._last = None
|
|
self._delay_skip = {id(st): len(st.real_delay_ms) for st in self._stats}
|
|
self.started_wall = self._wall()
|
|
|
|
def stage(self, name: str, ms: float, t: float | None = None) -> None:
|
|
if name == "capture":
|
|
self._cap_last = ms
|
|
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 = []
|
|
for st in self._stats:
|
|
v = st.real_delay_ms[self._delay_skip.get(id(st), 0):]
|
|
parts.append(np.asarray(v if last is None else v[-last:], np.float64))
|
|
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"),
|
|
"ended_unix": int(wall_end), # (for the launcher's Statistics view: "ended" is local time without a zone)
|
|
"game": os.environ.get("SUMMIT_GAME", "").strip() or None, # the launcher names the game it started
|
|
"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 second number for a row in Detailed (a stage's worst, the delay's 95th percentile)
|
|
detail_name: str = "" # what it is: "worst", "p95"
|
|
|
|
|
|
# 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), "%", "", "88"))
|
|
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)), "88.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)), "88.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)), "8.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"), "88"))
|
|
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(s["worst"]), "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)), "88",
|
|
_f(snap["delay_p95"], 0), "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)), "88"))
|
|
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 cost" if not inline else "cost", f"{snap['cost_us']:.1f}", "us/frame", "", "88.8"))
|
|
return out
|
|
|
|
|
|
def bench_cell(left_s: float) -> Cell:
|
|
"""The benchmark's countdown, always first."""
|
|
left = max(0, int(math.ceil(left_s)))
|
|
return Cell("bench", "benchmark", f"{left // 60}:{left % 60:02d}", "left", "tight", "8:88")
|
|
|
|
|
|
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
|