-
-
Save odashi/03a4d7b1901fe6e5c40b208ab2010507 to your computer and use it in GitHub Desktop.
Python: context manager to measure elapsed time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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