Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Created October 14, 2020 07:52
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 louisswarren/21a12a9857512b84922fe993cc4feeed to your computer and use it in GitHub Desktop.
Save louisswarren/21a12a9857512b84922fe993cc4feeed to your computer and use it in GitHub Desktop.
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