Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import random
- def performance_test():
- # Create test data
- n = 1000000 # size of data structure
- search_items = 1000 # number of lookups to perform
- # Generate random numbers for testing
- data = list(range(n))
- to_find = random.sample(range(n), search_items)
- # Test List
- print("\nTesting List Performance...")
- my_list = data
- start = time.time()
- for item in to_find:
- _ = item in my_list
- list_time = time.time() - start
- print(f"List search time: {list_time:.4f} seconds")
- # Test Set
- print("\nTesting Set Performance...")
- my_set = set(data)
- start = time.time()
- for item in to_find:
- _ = item in my_set
- set_time = time.time() - start
- print(f"Set search time: {set_time:.4f} seconds")
- # Test Dictionary
- print("\nTesting Dictionary Performance...")
- my_dict = {x: x for x in data}
- start = time.time()
- for item in to_find:
- try:
- _ = my_dict[item]
- except KeyError:
- pass
- dict_time = time.time() - start
- print(f"Dictionary search time: {dict_time:.4f} seconds")
- # Print comparison
- print(f"\nSet is {list_time/set_time:.0f}x faster than List")
- print(f"Dictionary is {list_time/dict_time:.0f}x faster than List")
- # Run the test
- performance_test()
- # Output
- Testing List Performance...
- List search time: 4.9485 seconds
- Testing Set Performance...
- Set search time: 0.0003 seconds
- Testing Dictionary Performance...
- Dictionary search time: 0.0005 seconds
- Set is 18615x faster than List
- Dictionary is 10404x faster than List
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement