Skip to content

Instantly share code, notes, and snippets.

@colesbury
Created December 22, 2025 16:11
Show Gist options
  • Select an option

  • Save colesbury/b675c95d35f29ca9d5723b95396d48a8 to your computer and use it in GitHub Desktop.

Select an option

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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment