Skip to content

Instantly share code, notes, and snippets.

@autf
Created September 16, 2022 09:55
Show Gist options
  • Save autf/034de601584c9dfeef8d94a2c9995e71 to your computer and use it in GitHub Desktop.
Save autf/034de601584c9dfeef8d94a2c9995e71 to your computer and use it in GitHub Desktop.
import timeit
import random
import array
setups = """xs = array('i', [0]) * n #array
xs = [0] * n #list
"""
# xs = [None] * n #list
# ^^^^ make no difference in timing
stmts = """for i in indices: xs[i] #rand read
for i in indices: xs[i] = i #rand write
for i in range(n): xs[i] #seq read
for i in range(n)[::-1]: xs[i] #seq read (rev)
for i in range(n): xs[i] = i #seq write
for i in range(n)[::-1]: xs[i] = i #seq write (rev)
"""
n = 10 ** 6
# n = int(2e5)
indices = [*range(n)]
random.shuffle(indices)
ts = []
for ln in stmts.splitlines():
stmt, tag = ln.split('#')
print(tag)
for ln in setups.splitlines():
setup, _tag = ln.split('#')
k, t = timeit.Timer(stmt,
setup=setup,
globals=dict(n=n, indices=indices, array=array.array)
).autorange()
t /= k
ts.append(t)
print(f'{t*1000: 7.1f} ms : {_tag}')
print(f'{ts[-2]/ts[-1]*100: 7.1f}%\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment