Created
February 8, 2023 10:46
-
-
Save hofrob/8b1c1e205a0d4c66a680b1fe4bfeba11 to your computer and use it in GitHub Desktop.
Compare timings of iterating over sets, lists, tuples and ranges
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 string | |
import time | |
import typing | |
def create_random_list(iterator_length: int) -> list[str]: | |
random_list = [] | |
for i in range(iterator_length): | |
random_list.append( | |
"".join(random.choices(string.ascii_letters + string.digits, k=10)) | |
) | |
return random_list | |
def time_iteration(value: typing.Iterable, count: int) -> int: | |
time_begin = time.monotonic_ns() | |
for i in range(count): | |
for _ in value: | |
... | |
timing = time.monotonic_ns() - time_begin | |
label = f"iterate {type(value)}" | |
print(f"{label:>20} {timing / 10 ** 6:.1f}ms") | |
return timing | |
def compare_timing(a: str, a_timing: int, b_timing: int) -> None: | |
a_vs_b = (b_timing - a_timing) / b_timing * 100 | |
print(f"{a} is {a_vs_b:.2f}% faster than a set") | |
def run() -> None: | |
iterator_length = 100 | |
n = 500000 | |
print(f"Iterate {n=} times over {iterator_length=} list items.") | |
print("---") | |
random_list = create_random_list(iterator_length) | |
list_timing = time_iteration(random_list, n) | |
tuple_timing = time_iteration(tuple(random_list), n) | |
range_timing = time_iteration(range(iterator_length), n) | |
set_timing = time_iteration(set(random_list), n) | |
compare_timing("list", list_timing, set_timing) | |
compare_timing("tuple", tuple_timing, set_timing) | |
compare_timing("range", range_timing, set_timing) | |
if __name__ == "__main__": | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result