Advertisement
here2share

# dict_order_vs_loop_order.py

Feb 4th, 2024
700
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. # dict_order_vs_loop_order.py
  2.  
  3. from time import perf_counter
  4.  
  5. old_list = ('a', 'b', 'a', 'b', 'c', 'a', '3', 'd', 'b', '2', 'e', 'c', 'a', '1', 'e', 'c', '3')
  6. for i in '.'*20:
  7.     print(tuple(dict.fromkeys(old_list)))
  8.  
  9. old_list = [old_list for _ in range(2_000_000)]
  10.  
  11. for i in '.'*60:
  12.     start = perf_counter()
  13.     new_list = tuple(dict.fromkeys(old_list))
  14.     dict_time = perf_counter()-start
  15.  
  16.     start = perf_counter()
  17.     new_list = []
  18.     for item in old_list:
  19.         if item not in new_list:
  20.             new_list.append(item)
  21.     loop_time = perf_counter()-start
  22.  
  23.     print(f"")
  24.     print(f"dict_time = {dict_time:0f}")
  25.     print(f"loop_time = {loop_time:0f}")
  26.     a, b = 'dict', 'loop'
  27.     t = dict_time/loop_time
  28.     if dict_time > loop_time:
  29.         a, b = b, a
  30.         t = loop_time/dict_time
  31.     print(f"{a} time is {t:0f} times faster then {b}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement