Files

54 lines
2.1 KiB
Python

"""GPU numbers for the Graphs stats overlay: utilisation, power, temperature, clock and memory from `nvidia-smi`, read
once a second on a thread of its own so the video loop never waits for it. No NVIDIA driver tools, or any trouble: the
numbers are simply missing (`latest` stays None) and the overlay leaves the row out."""
from __future__ import annotations
import collections
import subprocess
import sys
import threading
QUERY = "utilization.gpu,power.draw,temperature.gpu,memory.used,memory.total,clocks.sm"
class GpuStats:
def __init__(self, history: int = 120) -> None:
self.latest: dict | None = None # {"util", "power", "temp", "mem", "mem_total", "clock"}
self.util = collections.deque(maxlen=history)
self._proc = None
self._stop = False
threading.Thread(target=self._run, name="gpustats", daemon=True).start()
@staticmethod
def parse(line: str) -> dict | None:
"""One csv line (units off) as numbers; None if it isn't one."""
try:
u, p, t, m, mt, c = (float(x) for x in line.split(","))
except ValueError:
return None
return {"util": u, "power": p, "temp": t, "mem": m, "mem_total": mt, "clock": c}
def _run(self) -> None:
try:
flags = 0x08000000 if sys.platform == "win32" else 0 # no console window on Windows
self._proc = subprocess.Popen(
["nvidia-smi", f"--query-gpu={QUERY}", "--format=csv,noheader,nounits", "-l", "1"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, creationflags=flags)
for line in self._proc.stdout:
if self._stop:
break
d = self.parse(line)
if d is not None:
self.latest = d
self.util.append(d["util"])
except Exception: # noqa: BLE001 - no nvidia-smi: no GPU row
self.latest = None
def close(self) -> None:
self._stop = True
if self._proc is not None:
try:
self._proc.terminate()
except Exception: # noqa: BLE001
pass