GeezerVison is showing gist.github.com — bench.py
Instantly share code, notes, and snippets.
Created
December 22, 2025 16:11
-
Clone this repository at <script src="https://gist.github.com/colesbury/b675c95d35f29ca9d5723b95396d48a8.js"></script>
-
Save colesbury/b675c95d35f29ca9d5723b95396d48a8 to your computer and use it in GitHub Desktop.
Clone this repository at <script src="https://gist.github.com/colesbury/b675c95d35f29ca9d5723b95396d48a8.js"></script>
Save colesbury/b675c95d35f29ca9d5723b95396d48a8 to your computer and use it in GitHub Desktop.
|
import timeit |
|
|
|
def bench(n=100_000, reps=1_000): |
|
setups = { |
|
"begin": "lst = list(range(n))", |
|
"middle": "lst = list(range(n))", |
|
"end": "lst = list(range(n))", |
|
} |
|
|
|
stmts = { |
|
"begin": "lst.insert(0, -1)", |
|
"middle": "lst.insert(n//2, -1)", |
|
"end": "lst.insert(n, -1)", # same as append for a valid index at the end |
|
} |
|
|
|
for name in ("begin", "middle", "end"): |
|
t = timeit.timeit( |
|
stmt=stmts[name], |
|
setup=setups[name], |
|
number=reps, |
|
globals={"n": n}, |
|
) |
|
print(f"{name:6} n={n:<7} reps={reps:<7} total={t:.6f}s avg={t/reps*1e6:.2f}µs/op") |
|
|
|
if __name__ == "__main__": |
|
bench() |