Python: timing context manager
A quick post mostly for personal reference but that you may find useful…
A simple context manager that times how long it takes to execute a block of code, in wall clock time and cpu time.
import time
from contextlib import contextmanager
@contextmanager
def timed(name="", printer=print):
start_wall = time.perf_counter_ns()
start_cpu = time.process_time_ns()
try:
yield
finally:
took_wall = time.perf_counter_ns() - start_wall
took_cpu = time.process_time_ns() - start_cpu
name = name + ": " if name else ""
printer(f"{name}wall {took_wall/1e6:.3f} ms, cpu {took_cpu/1e6:.3f} ms")
Usage:
with timed("foo"):
time.sleep(1)
for _ in range(10_000_000):
pass
foo: wall 1553.276 ms, cpu 528.964 ms