Skip to content

Instantly share code, notes, and snippets.

@Girgitt
Created January 16, 2024 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Girgitt/831f909f5dab23e28f2222fbb14d2ef3 to your computer and use it in GitHub Desktop.
Save Girgitt/831f909f5dab23e28f2222fbb14d2ef3 to your computer and use it in GitHub Desktop.
text element search time in python: list vs. set
import timeit
import random
import string
# Function to generate random text of length 32
def generate_random_text():
return ''.join(random.choices(string.ascii_letters + string.digits, k=32))
# Generate a list of a couple of hundred random text values
random_text_list = [generate_random_text() for _ in range(400000)]
random_text_set = set(random_text_list)
# Function to search for a text in the list
def search_text_in_list(text):
return text in random_text_list
# Function to search for a text in the set
def search_text_in_set(text):
return text in random_text_set
# Profile the code using timeit
test_attempts = 1000
search_text = generate_random_text() # Replace with the text you want to search
time_taken = timeit.timeit(lambda: search_text_in_list(search_text), number=test_attempts)
time_taken_set = timeit.timeit(lambda: search_text_in_set(search_text), number=test_attempts)
print(f"Time taken to search for '{search_text}' in the list: {time_taken:.6f} seconds, {time_taken/test_attempts:.6f} per search")
print(f"Time taken to search for '{search_text}' in the set: {time_taken_set:.6f} seconds, {time_taken_set/test_attempts:.6f} per search")
print(f"Searching set is faster {time_taken/time_taken_set:.2f} times")
@Girgitt
Copy link
Author

Girgitt commented Jan 16, 2024

Time taken to search for '5cH8gIlXYLFBJlfzwR8GclSY43L9c3lq' in the list: 7.061913 seconds, 0.007062 per search
Time taken to search for '5cH8gIlXYLFBJlfzwR8GclSY43L9c3lq' in the set: 0.000223 seconds, 0.000000 per search
Searching set is faster 31628.20 times

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment