Debian Codegraph @

s_tui/builtin_stresser.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2017-2025 Alex Manuskin, Gil Tsuker
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
18
19 """Built-in Python CPU stresser using multiprocessing.
20
21 Provides a zero-external-dependency CPU stress test. Two workload strategies
22 are available, selectable at runtime:
23
24 1. numpy FP burn — mixed FMA/sqrt/sin on L2-resident arrays for maximum
25 sustained thermal output without triggering AVX-512 frequency penalties.
26 2. hashlib SHA-256 — stdlib fallback; tight C-backed loop on 64KB blocks.
27 """
28
29 from __future__ import annotations
30
31 import hashlib
32 import logging
33 from multiprocessing import Event, Process
34 from typing import TYPE_CHECKING
35
36 if TYPE_CHECKING:
37 from multiprocessing.synchronize import Event as EventType
38
39 try:
40 import numpy # noqa: F401 # pyright: ignore[reportMissingImports]
41
42 _HAS_NUMPY = True
43 except ImportError:
44 _HAS_NUMPY = False
45
46 STRATEGY_NUMPY = "numpy"
47 STRATEGY_HASHLIB = "hashlib"
48 STRATEGIES = [STRATEGY_NUMPY, STRATEGY_HASHLIB]
49
50 STRATEGY_LABELS = {
51 STRATEGY_NUMPY: "numpy FP burn",
52 STRATEGY_HASHLIB: "hashlib SHA-256",
53 }
54
55
56 def get_default_strategy() -> str:
57 """Return the best available strategy key."""
58 return STRATEGY_NUMPY if _HAS_NUMPY else STRATEGY_HASHLIB
59
60
61 def strategy_available(strategy: str) -> bool:
62 """Return True if the given strategy can actually run."""
63 if strategy == STRATEGY_NUMPY:
64 return _HAS_NUMPY
65 return True
66
67
68 def _worker_numpy(stop_event: EventType) -> None:
69 """CPU-intensive worker using mixed numpy FP operations.
70
71 Uses a combination of multiply, sqrt, add, and sin on arrays sized
72 to stay resident in L2 cache. This mix of instruction types keeps
73 power draw high without fully triggering AVX-512 frequency penalties
74 (which actually *reduce* thermal output). Benchmarks show this
75 approach matches external ``stress`` in temperature generation.
76 """
77 import numpy as np # pyright: ignore[reportMissingImports]
78
79 # 100K doubles = 800KB — fits in L2, large enough to minimize
80 # Python loop overhead relative to time spent in numpy C code.
81 size = 100_000
82 a = np.random.random(size) + 1.0
83 b = np.random.random(size) + 1.0
84 out = np.empty(size, dtype=np.float64)
85 while not stop_event.is_set():
86 np.multiply(a, b, out=out)
87 np.sqrt(out, out=out)
88 np.add(out, a, out=out)
89 np.sin(out, out=out)
90
91
92 def _worker_hashlib(stop_event: EventType) -> None:
93 """CPU-intensive worker using SHA-256 hashing."""
94 block = b"\x00" * 65536 # 64KB
95 while not stop_event.is_set():
96 hashlib.sha256(block).digest()
97
98
99 class BuiltinStresser:
100 """Manages CPU stress worker processes.
101
102 Uses multiprocessing.Event for clean shutdown signaling and a graduated
103 teardown (join → terminate → kill) to ensure workers are cleaned up.
104 """
105
106 def __init__(self) -> None:
107 self._stop_event: EventType | None = None
108 self._workers: list[Process] = []
109
110 def start(self, num_workers: int, strategy: str | None = None) -> None:
111 """Spawn *num_workers* CPU stress worker processes.
112
113 *strategy* selects the workload: ``STRATEGY_NUMPY`` or
114 ``STRATEGY_HASHLIB``. Falls back to hashlib if the requested
115 strategy is unavailable.
116 """
117 if strategy is None:
118 strategy = get_default_strategy()
119 if not strategy_available(strategy):
120 logging.warning(
121 "Strategy %s unavailable, falling back to hashlib", strategy
122 )
123 strategy = STRATEGY_HASHLIB
124
125 worker_fn = _worker_numpy if strategy == STRATEGY_NUMPY else _worker_hashlib
126
127 self.stop() # clean up any previous run
128 self._stop_event = Event()
129 try:
130 for _ in range(num_workers):
131 p = Process(target=worker_fn, args=(self._stop_event,), daemon=True)
132 p.start()
133 self._workers.append(p)
134 except OSError:
135 logging.exception(
136 "Failed to start all built-in stress workers; cleaning up %d "
137 "already-started workers",
138 len(self._workers),
139 )
140 self.stop()
141 raise
142 logging.info(
143 "Built-in stresser started %d workers (strategy: %s)",
144 num_workers,
145 STRATEGY_LABELS.get(strategy, strategy),
146 )
147
148 def stop(self, timeout: int = 3) -> None:
149 """Graduated teardown: signal → join → terminate → kill."""
150 if not self._workers:
151 return
152 if self._stop_event is not None:
153 self._stop_event.set()
154 for p in self._workers:
155 p.join(timeout=timeout)
156 for p in self._workers:
157 if p.is_alive():
158 logging.debug("Terminating straggler worker %s", p.pid)
159 p.terminate()
160 p.join(timeout=1)
161 for p in self._workers:
162 if p.is_alive():
163 logging.debug("Killing straggler worker %s", p.pid)
164 p.kill()
165 for p in self._workers:
166 p.join(timeout=1)
167 self._workers.clear()
168 logging.info("Built-in stresser stopped")
169
170 def is_running(self) -> bool:
171 """Return True if any worker process is still alive."""
172 return any(p.is_alive() for p in self._workers)