Created
May 4, 2011 03:07
-
-
Save jasongrout/954685 to your computer and use it in GitHub Desktop.
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 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