Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python benchmarker
from time import time, sleep
def runtime(f, retcont):
t = time()
r = f()
tt = time()
if retcont == []:
retcont.append(r)
elif retcont is not None:
assert(r == retcont[0])
return tt - t
def bench(*tasks, assert_equal=False, **named_tasks):
if callable(assert_equal) and not isinstance(assert_equal, bool):
named_tasks['assert_equal'] = assert_equal
assert_equal = False
if assert_equal:
retcont = []
else:
retcont = None
for i, task in enumerate(tasks):
print(f"Running task [{i}/{len(tasks)+len(named_tasks)}] ...", flush=True)
t = runtime(task, retcont)
print(f"\t{t} seconds elapsed. Done.")
print()
for name, task in named_tasks.items():
print(f"Running task [{i}/{len(tasks)+len(named_tasks)}]: {name} ...", flush=True)
t = runtime(task, retcont)
print(f"\t{t} seconds elapsed. Done.")
print()
msleep = lambda: sleep(0.001) or time()
bench(msleep, msleep, silly=msleep, bear=msleep, assert_equal=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment