Skip to content

Instantly share code, notes, and snippets.

@Shoeboxam
Created February 1, 2023 23:48
Show Gist options
  • Save Shoeboxam/421f11701be8a69cb26041e8aeeb5f07 to your computer and use it in GitHub Desktop.
Save Shoeboxam/421f11701be8a69cb26041e8aeeb5f07 to your computer and use it in GitHub Desktop.
simple memory+time benchmark
def bench(function, iterations):
import time
elapsed_times = []
import tracemalloc
tracemalloc.start()
for _ in range(iterations):
prev_snap = tracemalloc.take_snapshot()
prev_time = time.time()
function()
next_time = time.time()
next_snap = tracemalloc.take_snapshot()
elapsed_times.append(next_time - prev_time)
top_stat = next_snap.compare_to(prev_snap, 'lineno')[0]
print()
print(top_stat)
for line in top_stat.traceback.format():
print(line)
import matplotlib.pyplot as plt
plt.bar(range(iterations), elapsed_times)
plt.xlabel("iteration")
plt.ylabel("seconds elapsed")
bench(lambda: print("X"), iterations=5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment