Skip to content

Instantly share code, notes, and snippets.

@mesejo
Created November 2, 2021 15:39
Show Gist options
  • Save mesejo/87dcc99e1988491554a06995ed9b6dce to your computer and use it in GitHub Desktop.
Save mesejo/87dcc99e1988491554a06995ed9b6dce to your computer and use it in GitHub Desktop.
Code for reproducing the Benchmarks of https://stackoverflow.com/a/69812299/4001592
from operator import eq
from functools import partial
import perfplot
import random
def nested_list_comprehension(names, needle="Matt"):
return [[name for name in lst if needle == name] for lst in names]
def functional_approach(names, needle="Matt"):
eq_matt = partial(eq, needle)
return [[*filter(eq_matt, lst)] for lst in names]
def count_approach(names, needle="Matt"):
return [[needle] * name.count(needle) for name in names]
def setup(length):
population = ["Matt", "James", "William", "Charles", "Paul", "John", "JJ", "Peter", "George", "Edward", "Harry",
"Ronald", "Boris", "Donald"]
return [random.choices(population, k=10) for _ in range(length)]
def equality_check(a, b):
return a == b
if __name__ == "__main__":
b = perfplot.bench(
setup=setup,
kernels=[
nested_list_comprehension,
functional_approach,
count_approach
],
labels=["nested_list_comp", "functional", "count"],
n_range=[k for k in range(100, 1001, 100)],
xlabel="len(a)",
equality_check=equality_check
)
b.save("out.png")
b.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment