Skip to content

Instantly share code, notes, and snippets.

@jasongrout
Created May 4, 2011 03:07
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 jasongrout/954685 to your computer and use it in GitHub Desktop.
Save jasongrout/954685 to your computer and use it in GitHub Desktop.
import contextlib
@contextlib.contextmanager
def timing(results=None):
"""
Time the execution of the block of code. If a results list is
passed in, the time is appended to the list. Also returns a list
of one element containing the time the execution took.
To use, do something like:
from time import sleep
results_list=[]
with timing(results_list) as t:
sleep(1)
print results_list, t
Exceptions in the code should be re-raised and the timing should
correctly be set regardless of the exceptions.
"""
from time import time
try:
# code in the context is executed when we yield
start=[time()]
yield start
except:
# any exceptions in the code should get propagated
raise
finally:
start[0]=time()-start[0]
if results is not None:
results.extend(start)
repeats = []
timings = []
for i in range(10):
for j in range(1000):
with timing(timings):
fib(5)
repeats.append(sum(timings))
print repeats
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment