Skip to content

Instantly share code, notes, and snippets.

@odashi
Created December 24, 2022 00:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odashi/03a4d7b1901fe6e5c40b208ab2010507 to your computer and use it in GitHub Desktop.
Save odashi/03a4d7b1901fe6e5c40b208ab2010507 to your computer and use it in GitHub Desktop.
Python: context manager to measure elapsed time.
"""
This script will print:
INFO:root:test
INFO:root:elapsed: 3.003285470069386 (or something similar)
"""
from collections.abc import Callable, Iterator
from contextlib import contextmanager
import time
@contextmanager
def measure_time(callback: Callable[[float], None]) -> Iterator[None]:
begin = time.perf_counter()
try:
yield
finally:
callback(time.perf_counter() - begin)
import logging
logging.basicConfig(level=logging.INFO)
with measure_time(lambda t: logging.info(f"elapsed: {t}")):
time.sleep(3)
logging.info("test")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment