Last active
May 17, 2017 02:00
-
-
Save vlad-bezden/2c3fb12de38670e4768c61794be4e118 to your computer and use it in GitHub Desktop.
context based timer for calculating time
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(label: str): | |
'''Context Manager for calculating time. | |
Note: | |
code example is based on Python 3.6 | |
Args: | |
label (str): tag/label associated with timer | |
Yields: | |
tuple(str, float): label associated with calculation | |
and time calculation | |
Examples: | |
>>> a = range(1_000_000) | |
>>> b = range(1_000_000) | |
>>> with timer('array comparison') as comp: | |
print(a == b) | |
>>> label, time = comp() | |
>>> print(f'Total time for {label} {time:.6f} s') | |
''' | |
start = perf_counter() | |
yield lambda: (label, end - start) | |
end = perf_counter() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment