Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created July 17, 2020 15:04
Show Gist options
  • Save vlad-bezden/9d5181e218637c6ee16ce112eaa1b293 to your computer and use it in GitHub Desktop.
Save vlad-bezden/9d5181e218637c6ee16ce112eaa1b293 to your computer and use it in GitHub Desktop.
Simple timer example using contextmanager. The key here is to yield lambda. Return just value will not work
from time import perf_counter
from contextlib import contextmanager
@contextmanager
def timer() -> float:
start = perf_counter()
yield lambda: perf_counter() - start
# Usage example
with timer() as t:
import time
time.sleep(1)
print(f"Execution time: {t():.4f} secs")
# Output:
# Execution time: 1.0014 secs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment