Skip to content

Instantly share code, notes, and snippets.

@guyarad
Created February 8, 2017 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guyarad/ab5158684b85c89ae8c7bddc1a4c472f to your computer and use it in GitHub Desktop.
Save guyarad/ab5158684b85c89ae8c7bddc1a4c472f to your computer and use it in GitHub Desktop.
Timing context manager
@contextmanager
def timing(label=None, time_func=simulator.timestamp):
"""
Can be used in conjunction with ``with`` statement to easily measure duration.
Args:
time_func:
label: represents the measurement
Returns:
A callable. Once invoked will return one of the following (duration in seconds):
1. A tuple of ``label`` and duration, f ``label`` is not ``None``
2. Otherwise, returns the duration
Example:
>>> import math
>>> import time
>>> with timing('foo') as duration: # test timing with label
... time.sleep(1.3)
...
>>> d = duration()
>>> d[0]
'foo'
>>> round(math.fabs(d[1]-1.3), 2)
0.0
>>> with timing() as duration: # test timing without label
... time.sleep(0.4)
...
>>> round(math.fabs(duration()-0.4), 2)
0.0
"""
t0 = time_func()
yield lambda: (label, t1 - t0) if label is not None else (t1 - t0)
t1 = time_func()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment