WUT_Computer_Science/Programming/PORR/code/time_measurement.py
Krzysztof kuhy Rudnicki faef20dc45 PORR: zero findings, 18 tests still passing after every refactor
598 findings to none, and the suite ran through `./run.sh run` after each step
rather than at the end -- 18 passed, 27s, every time.

The shape of this one was different from the other courses. PORR is four
implementations of the same linear algebra (sequential, threads, processes,
dask), so nearly every finding came in groups of four:

- 229 missing annotations. Rather than `object`, which mypy strict rejects on
  every attribute access, each module declares what these actually are:
  `Matrix = np.ndarray | list[list[float]]` and the vector equivalent. The
  backends really are called with both -- comparing them is the point of the
  course.
- 76 names: `A` -> matrix, `Ab` -> augmented, `Ax` -> product, `I` ->
  identity, `dA` -> dask_matrix, and the two CamelCase functions. Renamed
  through `tokenize`, not regex, so no string or comment was touched.
- 121 missing docstrings, one per method name since the names repeat across
  all four backends.
- Seven functions over the argument limit, all taking the same seven or nine
  loose values. They are two frozen dataclasses now, in a new
  richardson_problem.py: `Problem(matrix, rhs, lambda_min, lambda_max)` and
  `Settings(max_iterations, x0, tol)`. `RichardsonMethod.__init__` also took a
  `size` argument it never read.
- threads_indep_old's iteration did "split into chunks, submit, wait" four
  times by hand (C901 11, PLR0915 54). One `_run_chunked` helper.
- tests.py's two bare asserts became explicit raises, per the no-ignores rule.
  `assert False` was also B011: `python -O` deletes it, so the non-convergence
  branch would have silently passed under optimisation.

Real fixes rather than style: np.random -> Generator, `os.path.exists` ->
Path, an `except Exception` around dask narrowed to the errors it actually
raises, and two runnable modules that logged at INFO without ever calling
basicConfig -- caught by scripts/check_refactor_safety.py, which is now doing
the job it was written for.

Repo-wide: 1,781 findings -> 1,183, all of them in the five courses left.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0172dj34FDpao6wsix8ZuCzE
2026-08-28 21:01:13 +02:00

89 lines
2.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Decorators that accumulate how long the measured calls take."""
import sys
import time
from collections.abc import Callable
class TimeAccumulator:
"""Total time spent inside the decorated functions."""
def __init__(self) -> None:
"""Set up the object."""
self.total_time = 0
class ComplexTimeAcumulator:
"""Per-lap and longest times for the decorated functions."""
def __init__(self) -> None:
"""Set up the object."""
self.hard_reset()
def hard_reset(self) -> None:
"""Clear every recorded time."""
self.total_time = 0
self.reset()
def reset(self) -> None:
"""Clear the current lap."""
self.lap_time = 0
self.start = sys.float_info.max
self.end = 0
def save_lap_and_reset(self) -> None:
"""Store the current lap and start a new one."""
self.total_time += self.lap_time
self.reset()
time_accumulator = TimeAccumulator()
tests_time = TimeAccumulator()
longest_threads_time_accumulator = ComplexTimeAcumulator()
def time_measurement(accumulator: TimeAccumulator) -> Callable[..., object]:
"""Decorate a function so its runtime accumulates."""
def decorator(func: Callable[..., object]) -> Callable[..., object]:
"""Wrap the function so its runtime is recorded."""
def inner(*args: object, **kwargs: object) -> object:
"""Call the wrapped function and record how long it took."""
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
accumulator.total_time += end - start
return result
return inner
return decorator
def time_measurement_longest(
accumulator: ComplexTimeAcumulator,
) -> Callable[..., object]:
"""Decorate a function so its longest runtime is kept."""
def decorator(func: Callable[..., object]) -> Callable[..., object]:
"""Wrap the function so its runtime is recorded."""
def inner(*args: object, **kwargs: object) -> object:
"""Call the wrapped function and record how long it took."""
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
accumulator.start = min(accumulator.start, start)
accumulator.end = max(accumulator.end, end)
accumulator.lap_time = (
accumulator.end - accumulator.start
) # "=" instead of "+="
return result
return inner
return decorator