Advertisement
VikkaLorel

list comprehension perf with filter

Jan 20th, 2020
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. from timeit import timeit
  2.  
  3.  
  4. def setup():
  5.     cities_hab = dict({
  6.         "Chicago": 9_526_434,
  7.     "Londre": 14_257_962,
  8.     "Lyon": 513_275,
  9.     "Xi'an": 8_467_837,
  10.         })
  11.     return cities_hab
  12.  
  13.  
  14. def do_nothing(name):
  15.     pass
  16.  
  17. def without_lc(cities_hab):
  18.     for city_name, city_hab in cities_hab.items():
  19.         if city_hab >= 1_000_000:
  20.             do_nothing(city_name)
  21.  
  22.  
  23. def with_lc(cities_hab):
  24.     [do_nothing(city_name) for city_name, city_hab in cities_hab.items()
  25.      if city_hab >= 1_000_000]
  26.  
  27.  
  28. if __name__ == '__main__':
  29.     t1 = timeit('without_lc(cities_hab)',
  30.                 setup='from __main__ import without_lc, do_nothing, setup; cities_hab = setup()',
  31.                 number=100000)
  32.     t2 = timeit('with_lc(cities_hab)',
  33.                 setup='from __main__ import with_lc, do_nothing, setup; cities_hab = setup()',
  34.                 number=100000)
  35.     print(t1, t2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement