Last active
April 1, 2019 23:19
-
-
Save juanarrivillaga/d7cdf5e72fbe2db80ef342aa7d7437af to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import matplotlib.pyplot as plt | |
import time | |
def filter_items_newlist(items, item): | |
return [x for x in items if x != item] | |
def filter_items_inplace_gen(items, item): | |
items[:] = (x for x in items if x != item) | |
def filter_items_inplace(items, item): | |
ix_dst = 0 | |
for ix_src, x in enumerate(items): | |
if x != item: | |
items[ix_dst] = x | |
ix_dst += 1 | |
del items[ix_dst:] | |
def time_func(N, f): | |
items = list(range(N)) | |
start = time.perf_counter() | |
f(items, N) | |
stop = time.perf_counter() | |
return stop - start | |
NS = range(0, 1_000_000, 10_000) | |
inplc = [time_func(n, filter_items_inplace) for n in NS] | |
inplc_gen = [time_func(n, filter_items_inplace_gen) for n in NS] | |
new = [time_func(n, filter_items_newlist) for n in NS] | |
df = pd.DataFrame({"in-place":inplc, "in-place-gen": inplc_gen, "new-list":new}, index=NS) | |
df.plot() | |
plt.savefig('in-place-vs-new-list-filter.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, this is really the best-case difference for the in-place algorithm, since nothing is actually removed, since N is never in the list!