Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,10 @@ runs spaced with `.with_cooldown(s)`, and a suite's order randomized with
sources, exiting non-zero on a high-severity one. On Linux as root, `bench
denoise minimize|restore|status` quiets those knobs and reverts them.
`bench run --check-environment` / `--denoise` do the same around a run;
scripts use `bench_app(probe=SystemProbe(), denoise=True)`.
scripts use `bench_app(probe=SystemProbe(), denoise=True)`. During a run,
`Thermal()` (added as both a hook and a metric) records each execution's hottest
CPU package temperature and thermal-throttle events on Linux, flagging the
samples `suspect` when the CPU throttled or ran near its limit.

## Development

Expand Down
2 changes: 2 additions & 0 deletions src/bench/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
RegexMetric,
RUsage,
SystemTime,
Thermal,
Time,
UserTime,
as_metric_source,
Expand Down Expand Up @@ -234,6 +235,7 @@
"SystemTime",
"RUsage",
"max_rss",
"Thermal",
"RebenchMetric",
"RegexMetric",
"FloatPerLine",
Expand Down
2 changes: 2 additions & 0 deletions src/bench/core/metric/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from bench.core.metric.rebench import RebenchMetric
from bench.core.metric.regex import RegexMetric
from bench.core.metric.rusage import RUsage, max_rss
from bench.core.metric.thermal import Thermal
from bench.core.metric.time import SystemTime, Time, UserTime

__all__ = [
Expand All @@ -18,6 +19,7 @@
"SystemTime",
"RUsage",
"max_rss",
"Thermal",
"RebenchMetric",
"RegexMetric",
"FloatPerLine",
Expand Down
161 changes: 161 additions & 0 deletions src/bench/core/metric/thermal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
"""CPU temperature and thermal throttling during each execution.

A hot or throttled CPU runs slower, so the measurements taken on it are
suspect. `Thermal` is both a `Hook` and a `Metric`; add the same object as
each::

t = Thermal()
bench("x").with_hook(t).with_metric(t)

It emits two process samples, `cpu_temp_max` (C) and `cpu_throttle` (throttle
events), marked `extra={"suspect": True}` when the CPU throttled or came within
`margin` degrees of a limit the hardware declares. On Linux it reads the CPU's
hwmon and thermal-zone sensors and the kernel's throttle counters; where they
are missing it emits nothing, and a sensor that fails never fails a benchmark.
"""

from __future__ import annotations

import threading
from collections.abc import Iterable
from pathlib import Path
from typing import TYPE_CHECKING

from bench.core.hook import Hook
from bench.core.metric.base import Metric
from bench.model.invocation import InvocationResult
from bench.model.results import Sample

if TYPE_CHECKING:
from bench.model.benchmark import Benchmark

# hwmon drivers of CPU packages, and the labels of their package sensors
_HWMON = {"coretemp": ("Package id",), "k10temp": ("Tctl", "Tdie")}
# thermal zones that measure the CPU, by their type
_ZONES = ("cpu", "pkg", "soc")
_TRIPS = ("passive", "hot", "critical")

type Sensor = tuple[Path, int | None] # its reading, and its limit in m°C


def _text(path: Path) -> str:
try:
return path.read_text().strip()
except (OSError, UnicodeDecodeError):
return ""


def _int(path: Path) -> int | None:
try:
return int(_text(path))
except ValueError:
return None


def cpu_sensors(sysfs: Path = Path("/sys")) -> list[Sensor]:
"""The CPU temperature sensors, each with the limit it declares."""
sensors: list[Sensor] = []
for hwmon in sorted(sysfs.glob("class/hwmon/hwmon*")):
labels = _HWMON.get(_text(hwmon / "name"))
for label in sorted(hwmon.glob("temp*_label")) if labels else []:
if _text(label).startswith(labels or ()):
base = str(label).removesuffix("_label")
sensors.append((Path(f"{base}_input"), _int(Path(f"{base}_crit"))))
if sensors:
# where a driver covers the package, thermal zones add only firmware
# policy zones, whose trip points are not CPU limits
return sensors
for zone in sorted(sysfs.glob("class/thermal/thermal_zone*")):
if any(z in _text(zone / "type").lower() for z in _ZONES):
trips = [
_int(Path(str(t).replace("_type", "_temp")))
for t in zone.glob("trip_point_*_type")
if _text(t) in _TRIPS
]
limits = [t for t in trips if t is not None and t > 0]
sensors.append((zone / "temp", min(limits, default=None)))
return sensors


def throttle_events(sysfs: Path = Path("/sys")) -> int | None:
"""Thermal-throttle events counted so far, summed over all CPUs."""
files = sysfs.glob("devices/system/cpu/cpu[0-9]*/thermal_throttle/*_throttle_count")
counts = [c for c in map(_int, files) if c is not None]
return sum(counts) if counts else None


class _Watch:
"""Samples the sensors every `interval` seconds until stopped."""

def __init__(self, thermal: Thermal) -> None:
self.thermal = thermal
self.hottest: int | None = None
self.hot = False
self.throttles_before = throttle_events(thermal.sysfs)
self.throttles: int | None = None
self._stop = threading.Event()
self._sample()
self._thread = threading.Thread(target=self._loop, daemon=True)
self._thread.start()

def _sample(self) -> None:
for path, limit in self.thermal.sensors:
if (t := _int(path)) is None:
continue
self.hottest = t if self.hottest is None else max(self.hottest, t)
if limit is not None and t >= limit - self.thermal.margin * 1000:
self.hot = True

def _loop(self) -> None:
while not self._stop.wait(self.thermal.interval):
self._sample()

def stop(self) -> None:
self._stop.set()
self._thread.join()
self._sample()
after = throttle_events(self.thermal.sysfs)
if self.throttles_before is not None and after is not None:
self.throttles = after - self.throttles_before


class Thermal(Hook, Metric):
"""CPU temperature and thermal throttling around each execution."""

def __init__(
self, interval: float = 1.0, margin: float = 10.0, sysfs: Path = Path("/sys")
) -> None:
Metric.__init__(self, "cpu_temp_max", "C")
self.interval, self.margin, self.sysfs = interval, margin, sysfs
try:
self.sensors = cpu_sensors(sysfs)
self.observable = bool(self.sensors) or throttle_events(sysfs) is not None
except Exception:
self.sensors, self.observable = [], False
self._local = threading.local() # executions may run in parallel threads

def setup(self, benchmark: Benchmark) -> None:
self._local.watch = None
if self.observable:
try:
self._local.watch = _Watch(self)
except Exception:
pass

def teardown(self, benchmark: Benchmark) -> None:
if (watch := getattr(self._local, "watch", None)) is not None:
watch.stop()

def process(self, data: InvocationResult) -> Iterable[Sample]:
watch: _Watch | None = getattr(self._local, "watch", None)
self._local.watch = None
if watch is None:
return
suspect = watch.hot or (watch.throttles or 0) > 0
extra = {"suspect": True} if suspect else {}
if watch.hottest is not None:
yield self.get_sample(watch.hottest / 1000, extra=extra)
if watch.throttles is not None:
yield self.get_sample(
float(watch.throttles), "cpu_throttle", "", extra=extra
)
139 changes: 139 additions & 0 deletions tests/test_thermal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"""Thermal: CPU temperature and throttling around each execution, read from a
fake sysfs tree."""

from collections.abc import Callable
from pathlib import Path
from typing import Any

from bench import Controller, FixedRuns, Reporter, Thermal, bench, suite
from bench.builder.suite import plan
from bench.model.invocation import InvocationResult
from bench.params import Params


def _write(root: Path, files: dict[str, str]) -> Path:
for name, content in files.items():
(root / name).parent.mkdir(parents=True, exist_ok=True)
(root / name).write_text(content)
return root


def _coretemp(root: Path, temp: int = 50000, throttles: int = 0) -> Path:
return _write(
root,
{
"class/hwmon/hwmon2/name": "coretemp\n",
"class/hwmon/hwmon2/temp1_label": "Package id 0\n",
"class/hwmon/hwmon2/temp1_input": f"{temp}\n",
"class/hwmon/hwmon2/temp1_crit": "100000\n",
"class/hwmon/hwmon2/temp2_label": "Core 0\n", # not the package
"class/hwmon/hwmon2/temp2_input": "99000\n",
"devices/system/cpu/cpu0/thermal_throttle/core_throttle_count": f"{throttles}\n",
"devices/system/cpu/cpu0/thermal_throttle/package_throttle_count": "0\n",
},
)


def _measure(t: Thermal, during: Callable[[], Any] = lambda: None) -> dict[str, Any]:
t.setup(None) # type: ignore[arg-type]
during()
t.teardown(None) # type: ignore[arg-type]
samples = t.process(InvocationResult.__new__(InvocationResult))
return {s.metric: (s.value, dict(s.extra)) for s in samples}


def test_cool_and_unthrottled(tmp_path: Path):
t = Thermal(sysfs=_coretemp(tmp_path))
assert _measure(t) == {"cpu_temp_max": (50.0, {}), "cpu_throttle": (0.0, {})}


def test_near_the_declared_limit_is_suspect(tmp_path: Path):
root = _coretemp(tmp_path)
got = _measure(Thermal(sysfs=root), lambda: _coretemp(root, temp=93000))
assert got["cpu_temp_max"] == (93.0, {"suspect": True}) # within 10 C of crit


def test_throttling_is_suspect(tmp_path: Path):
root = _coretemp(tmp_path, throttles=4)
got = _measure(Thermal(sysfs=root), lambda: _coretemp(root, throttles=6))
assert got["cpu_throttle"] == (2.0, {"suspect": True})


def test_thermal_zone_uses_its_lowest_trip_point(tmp_path: Path):
root = _write(
tmp_path,
{
"class/thermal/thermal_zone0/type": "cpu-thermal\n",
"class/thermal/thermal_zone0/temp": "77000\n",
"class/thermal/thermal_zone0/trip_point_0_type": "active\n", # a fan, not a limit
"class/thermal/thermal_zone0/trip_point_0_temp": "60000\n",
"class/thermal/thermal_zone0/trip_point_1_type": "passive\n",
"class/thermal/thermal_zone0/trip_point_1_temp": "85000\n",
"class/thermal/thermal_zone0/trip_point_2_type": "critical\n",
"class/thermal/thermal_zone0/trip_point_2_temp": "105000\n",
"class/thermal/thermal_zone1/type": "battery\n", # not the CPU
"class/thermal/thermal_zone1/temp": "99000\n",
},
)
assert _measure(Thermal(sysfs=root)) == {"cpu_temp_max": (77.0, {"suspect": True})}


def test_thermal_zones_are_ignored_where_hwmon_covers_the_cpu(tmp_path: Path):
root = _write(
_coretemp(tmp_path),
{
"class/thermal/thermal_zone0/type": "CPUV\n", # a firmware policy zone
"class/thermal/thermal_zone0/temp": "55000\n",
"class/thermal/thermal_zone0/trip_point_0_type": "passive\n",
"class/thermal/thermal_zone0/trip_point_0_temp": "60050\n",
},
)
assert _measure(Thermal(sysfs=root))["cpu_temp_max"] == (50.0, {})


def test_without_a_declared_limit_nothing_is_guessed(tmp_path: Path):
root = _write(
tmp_path,
{
"class/hwmon/hwmon0/name": "k10temp\n",
"class/hwmon/hwmon0/temp1_label": "Tctl\n",
"class/hwmon/hwmon0/temp1_input": "99000\n",
},
)
assert _measure(Thermal(sysfs=root)) == {"cpu_temp_max": (99.0, {})}


def test_no_sensors_no_samples(tmp_path: Path):
t = Thermal(sysfs=tmp_path)
assert not t.observable
assert _measure(t) == {}


def test_broken_sensors_never_raise(tmp_path: Path):
root = _write(
tmp_path,
{
"class/hwmon/hwmon0/name": "coretemp\n",
"class/hwmon/hwmon0/temp1_label": "Package id 0\n",
"class/hwmon/hwmon0/temp1_input": "garbage\n",
"class/hwmon/hwmon0/temp1_crit": "\xff\n",
"class/thermal/thermal_zone0/type": "x86_pkg_temp\n",
"devices/system/cpu/cpu0/thermal_throttle/core_throttle_count": "n/a\n",
},
)
(root / "class/thermal/thermal_zone0/temp").mkdir() # unreadable as a file
assert _measure(Thermal(sysfs=root)) == {}


def test_as_hook_and_metric_of_a_benchmark(tmp_path: Path):
t = Thermal(sysfs=_coretemp(tmp_path, temp=61000))
b = bench("b").with_command(["true"]).with_hook(t).with_metric(t)
s = suite("S").add(b).with_cwd(Path("/tmp")).with_runs(FixedRuns(2))

executions = Controller().run_benchmark(plan([s], Params())[0], Reporter(), False)

for e in executions:
assert {x.metric: x.value for x in e.process_samples} == {
"cpu_temp_max": 61.0,
"cpu_throttle": 0.0,
}
Loading