Advertisement
GeorgiLukanov87

sets and dicts are faster than list in python

Oct 24th, 2024 (edited)
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. import time
  2. import random
  3.  
  4. def performance_test():
  5.     # Create test data
  6.     n = 1000000  # size of data structure
  7.     search_items = 1000  # number of lookups to perform
  8.    
  9.     # Generate random numbers for testing
  10.     data = list(range(n))
  11.     to_find = random.sample(range(n), search_items)
  12.    
  13.     # Test List
  14.     print("\nTesting List Performance...")
  15.     my_list = data
  16.     start = time.time()
  17.     for item in to_find:
  18.         _ = item in my_list
  19.     list_time = time.time() - start
  20.     print(f"List search time: {list_time:.4f} seconds")
  21.    
  22.     # Test Set
  23.     print("\nTesting Set Performance...")
  24.     my_set = set(data)
  25.     start = time.time()
  26.     for item in to_find:
  27.         _ = item in my_set
  28.     set_time = time.time() - start
  29.     print(f"Set search time: {set_time:.4f} seconds")
  30.    
  31.     # Test Dictionary
  32.     print("\nTesting Dictionary Performance...")
  33.     my_dict = {x: x for x in data}
  34.     start = time.time()
  35.     for item in to_find:
  36.         try:
  37.             _ = my_dict[item]
  38.         except KeyError:
  39.             pass
  40.     dict_time = time.time() - start
  41.     print(f"Dictionary search time: {dict_time:.4f} seconds")
  42.    
  43.     # Print comparison
  44.     print(f"\nSet is {list_time/set_time:.0f}x faster than List")
  45.     print(f"Dictionary is {list_time/dict_time:.0f}x faster than List")
  46.  
  47. # Run the test
  48. performance_test()
  49. # Output
  50.  
  51. Testing List Performance...
  52. List search time: 4.9485 seconds
  53.  
  54. Testing Set Performance...
  55. Set search time: 0.0003 seconds
  56.  
  57. Testing Dictionary Performance...
  58. Dictionary search time: 0.0005 seconds
  59.  
  60. Set is 18615x faster than List
  61. Dictionary is 10404x faster than List
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement