Created
April 14, 2020 19:15
-
-
Save Sasszem/d8708652059ef3da3674b0e299542886 to your computer and use it in GitHub Desktop.
Quadratic vs linear time complexity showcase
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 random | |
import timeit | |
def setup_map(data, num): | |
for _ in range(num): | |
data[random.random()] = random.random() | |
map = {} | |
setup_map(map, 100000) | |
def lookup(data): | |
try: | |
data[random.random()] | |
except: | |
pass | |
dt = timeit.timeit("lookup(map)", number=10000, globals=globals()) | |
print(f"Random lookups in dict: {dt} seconds") | |
map = [] | |
def setup_kv(data, num): | |
for _ in range(num): | |
data.append((random.random(), random.random())) | |
setup_kv(map, 100000) | |
def lookup_kv(data): | |
key = random.random() | |
for e in data: | |
if e[0]==key: | |
break | |
dt2 = timeit.timeit("lookup_kv(map)", number=10000, globals=globals()) | |
print(f"Random lookups in linear: {dt2} seconds") | |
print(f"Ratio: {dt2/dt}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment