Skip to content

Instantly share code, notes, and snippets.

@juanarrivillaga
Created October 1, 2021 21:57
Show Gist options
  • Save juanarrivillaga/c0910cee9f824eb2075f265fb63f238f to your computer and use it in GitHub Desktop.
Save juanarrivillaga/c0910cee9f824eb2075f265fb63f238f to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
import pandas as pd
from timeit import timeit
setup = """
def list_comp(d):
return [ (x*2)/3 for x in d ]
def pre_allocate(d):
result = [None]*len(d)
for i, x in enumerate(d):
result[i] = (x*2)/3
return result
d = list(range({}))
"""
lc = [timeit("list_comp(d)", setup=setup.format(n), number=10) for n in N]
pa = [timeit("pre_allocate(d)", setup=setup.format(n), number=10) for n in N]
pd.DataFrame(dict(pre_allocate=pa, list_comp=lc), index=N).plot()
plt.savefig("pre-allocate-vs-list-comp.png")
@juanarrivillaga
Copy link
Author

pre-allocate-vs-list-comp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment