Created
February 16, 2015 13:48
-
-
Save danbradham/97b04bdf70be8c5390dd to your computer and use it in GitHub Desktop.
Context manager for timing code execution.
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
import time | |
import sys | |
from contextlib import contextmanager | |
@contextmanager | |
def stopwatch(label, width=20): | |
''' | |
A context manager that prints out the execution time of the nested code. | |
''' | |
plat = sys.platform.rstrip('0123456789') | |
time_fn = time.clock if plat == 'win' else time.time | |
start = time_fn() | |
try: | |
yield | |
finally: | |
print '{:<{w}}: {}'.format(label, time_fn() - start, w=width) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment