Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Last active May 17, 2017 02:00
Show Gist options
  • Save vlad-bezden/2c3fb12de38670e4768c61794be4e118 to your computer and use it in GitHub Desktop.
Save vlad-bezden/2c3fb12de38670e4768c61794be4e118 to your computer and use it in GitHub Desktop.
context based timer for calculating time
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