Created
February 8, 2017 06:23
-
-
Save guyarad/ab5158684b85c89ae8c7bddc1a4c472f to your computer and use it in GitHub Desktop.
Timing context manager
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
@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