Skip to content

Instantly share code, notes, and snippets.

@b4tman
Last active September 30, 2021 12:52
Show Gist options
  • Save b4tman/4d05d61a16b5909cdf41e26cd1c066ef to your computer and use it in GitHub Desktop.
Save b4tman/4d05d61a16b5909cdf41e26cd1c066ef to your computer and use it in GitHub Desktop.
import time
import statistics
import functools
def bench(num_iters = 1000):
def make_wrapper(func):
@functools.wraps(func)
def wrapper(*args, **kw):
times = []
for _ in range(num_iters):
t0 = time.perf_counter_ns()
result = func(*args, **kw)
t1 = time.perf_counter_ns()
times.append(t1 - t0)
best = min(times)
avg = round(sum(times) / num_iters, 2)
median = statistics.median(times)
print(f'{func.__name__} x {num_iters} => best: {best} ns, \tavg: {avg} ns, \tmedian: {median} ns')
return result
return wrapper()
return make_wrapper
@bench
def long_func():
for i in range(23434):
x = i**2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment