Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"""
The results of the script are used in blog article called
"Revisiting the Mechanism Behind the `for` Statement" hosted at
https://mylette.rs/revisiting-the-mechanism-behind-the-for-statement.
Purpose: The script measures the performance of iterating over all
elements in an iterable with two different implementation methods, namely
using Pythonic and non-Pythonic design patterns. See functions
`loop_pythonic` and `loop_with_indexes` for details.
Requirements: Python version >= 3.3
License: MIT License (see https://opensource.org/licenses/MIT)
"""
from functools import wraps
from time import perf_counter
ITERABLE = range(1000000) # <-- change here e.g. ITERABLE = list(range(1000000))
def timeit(func):
"""Minimalistic decorator for timing the performance of `func`"""
@wraps(func)
def chronometer(*args):
t1 = perf_counter()
rv = func(*args)
t2 = perf_counter()
print("{:=^40}".format(func.__qualname__))
print(f"Elapsed time: {t2 - t1} s")
return rv
return chronometer
@timeit
def loop_for(iterable):
"""Retrieve elements of `iterable` with the for-loop
Demonstrates the Pythonic way of iterating over objects.
"""
for item in iterable:
item
return None
@timeit
def loop_indexes(iterable):
"""Retrieve elements of `iterable` with indexes
Demonstrates non-Pythonic way of iterating over objects.
"""
for index in range(len(iterable)):
iterable[index]
return None
@timeit
def loop_while(iterable):
"""Retrieve elements of `iterable` with the while-loop
Demonstrates the mechanism behind the for-loop.
"""
_i = iter(iterable)
_loop = True
while _loop:
try:
item = next(_i)
except StopIteration:
_loop = False
else:
item
return None
if __name__ == "__main__":
loop_for(ITERABLE)
loop_indexes(ITERABLE)
loop_while(ITERABLE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.