Skip to content

Instantly share code, notes, and snippets.

@raymondbutcher
Last active December 14, 2015 23:49
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 raymondbutcher/5168588 to your computer and use it in GitHub Desktop.
Save raymondbutcher/5168588 to your computer and use it in GitHub Desktop.
A Python context which can be used to easily time blocks of code.
import sys
import time
from contextlib import contextmanager
@contextmanager
def time_elapsed(name=''):
"""
A context manager for timing blocks of code.
From https://gist.github.com/raymondbutcher/5168588
"""
start = time.time()
yield
elapsed = (time.time() - start) * 1000
if name:
sys.stderr.write('%s took ' % name)
if elapsed < 1:
sys.stderr.write('%.4f ms\n' % elapsed)
else:
sys.stderr.write('%d ms\n' % elapsed)
@raymondbutcher
Copy link
Author

Usage:

>>> with time_elapsed('sleeping'):
...     time.sleep(2)
... 
sleeping took 2001 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment