TimeRun — Structured timing for Python.
TimeRun is a single-file Python package with no dependencies beyond the standard library. It records wall-clock time and CPU time when you measure a block or function calls (one Measurement per block or per call) and supports optional metadata (e.g. run id, tags) and callbacks (on_start / on_end) per measurement.
For positioning and the full value proposition, see Overview on the docs site.
From PyPI:
pip install timerunFrom source:
pip install git+https://github.com/HH-MWB/timerun.gitNote: Requires Python 3.10+.
Use with Timer() as m: (or async with). The yielded Measurement has wall_time and cpu_time:
>>> from timerun import Timer
>>> with Timer() as m:
... pass # code block to be measured
...
>>> m.wall_time.timedelta
datetime.timedelta(microseconds=11)
>>> m.cpu_time.timedelta
datetime.timedelta(microseconds=8)Note: On block exit the timer records CPU time first, then wall time, so wall time is slightly larger than CPU time even when there is no I/O or scheduling.
Use @Timer(). One Measurement per call is appended to the callable’s measurements deque:
>>> from timerun import Timer
>>> @Timer()
... def func(): # function to be measured
... return
...
>>> func()
>>> func.measurements[-1].wall_time.timedelta
datetime.timedelta(microseconds=11)
>>> func.measurements[-1].cpu_time.timedelta
datetime.timedelta(microseconds=8)Note: Argument maxlen caps how many measurements are kept (e.g. @Timer(maxlen=10)). By default the deque is unbounded.
Optional on_start and on_end callbacks run once per measurement. Both receive the Measurement instance — on_start before timings are set, on_end after. For example:
Print elapsed time when a block finishes:
>>> from timerun import Timer
>>> with Timer(on_end=lambda m: print(m.wall_time.timedelta)):
... pass # code block to be measured
...
0:00:00.000008Attach a trace id before each call starts:
>>> from uuid import uuid4
>>> from timerun import Timer
>>> @Timer(on_start=lambda m: m.metadata.update(trace_id=uuid4().hex))
... def func():
... return
...
>>> func()
>>> func.measurements[-1].metadata
{'trace_id': '8aa2c000c98843738a2f0d5d3600d052'}Contributions are welcome. See CONTRIBUTING.md for setup, testing, and pull request guidelines.
This project is licensed under the MIT License — see the LICENSE file for details.