Skip to content

Instantly share code, notes, and snippets.

@danbradham
Created February 16, 2015 13:48
Show Gist options
  • Save danbradham/97b04bdf70be8c5390dd to your computer and use it in GitHub Desktop.
Save danbradham/97b04bdf70be8c5390dd to your computer and use it in GitHub Desktop.
Context manager for timing code execution.
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