Created
September 24, 2020 19:56
-
-
Save cnnrznn/7af599f37605c95025e1f5c5b7f22c60 to your computer and use it in GitHub Desktop.
Timing comparison of membership lookup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from random import randint | |
num_items = 1000000 | |
num_iters = 1000 | |
randoms_list = [randint(0, 1000000) for i in range(num_items)] | |
randoms_dict = {num: True for num in randoms_list} | |
randoms_set = {num for num in randoms_list} | |
time_start = time.time() | |
for i in range(num_iters): | |
# -1 is definitely not present, therefore 'in' will scan the entire list | |
if -1 in randoms_list: | |
pass | |
print("List operations in", time.time() - time_start) | |
time_start = time.time() | |
for i in range(num_iters): | |
# in a dictionary, 'in' is a O(1) lookup | |
if -1 in randoms_dict: | |
pass | |
print("Dict operations in", time.time() - time_start) | |
time_start = time.time() | |
for i in range(num_iters): | |
# in a set, 'in' is a O(1) lookup | |
if -1 in randoms_set: | |
pass | |
print("Set operations in", time.time() - time_start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment