Skip to content

Instantly share code, notes, and snippets.

@egregius313
Last active February 27, 2017 15:29
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 egregius313/0a2f49e17b2f8a63ba7a9f9683b178b4 to your computer and use it in GitHub Desktop.
Save egregius313/0a2f49e17b2f8a63ba7a9f9683b178b4 to your computer and use it in GitHub Desktop.
Simple context manager for timing Python code
#!/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