Created
July 17, 2020 15:04
-
-
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
This file contains hidden or 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
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