Here is an answer using:
- a concise context manager to time code snippets
time.perf_counter()to compute time delta. It should be preferred as it is not adjustable (neither a sysadmin nor a daemon can change its value) contrary totime.time()(see doc)
import time from collections.abc import Iterator from contextlib import contextmanager @contextmanager def time_it() -> Iterator[None]: tic: float = time.perf_counter() try: yield finally: toc: float = time.perf_counter() print(f"Computation time = {1000*(toc - tic):.3f}ms") An example how to use it:
# Example: vector dot product computation with time_it(): A = B = range(10000001_000_000) dot = sum(a*b for a,b in zip(A,B)) # Computation time = 95.353ms Appendix
import time # to check adjustability assert time.get_clock_info('time').adjustable assert time.get_clock_info('perf_counter').adjustable is False