Last active
February 27, 2017 15:29
-
-
Save egregius313/0a2f49e17b2f8a63ba7a9f9683b178b4 to your computer and use it in GitHub Desktop.
Simple context manager for timing Python code
This file contains 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
#!/usr/bin/env python | |
from contextlib import contextmanager | |
import time | |
@contextmanager | |
def timethis(timer=time.perf_counter): | |
""" | |
Small timing function. It is meant to be used as a | |
context manager, and it returns a lambda that when | |
called returns the time it took for the block to | |
execute. | |
>>> from time import sleep | |
>>> with timethis() as timer: | |
... sleep(4.5) | |
... | |
>>> print('Finished in %.4f seconds.' % timer()) | |
Finished in 4.5017 seconds. | |
""" | |
start = timer() | |
try: | |
yield lambda: end - start | |
finally: | |
end = timer() | |
if __name__ == '__main__': | |
with timethis() as timer: | |
for i in range(20): | |
print(i) | |
print('Operation took', timer(), 'seconds.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment