Created
August 25, 2023 05:47
-
-
Save fcamel/fca556c107d5272ebcd64bd8f935534f to your computer and use it in GitHub Desktop.
benchmark range + array index vs. zip
This file contains hidden or 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
# Result on Mac Mini M2 Pro: | |
# | |
# use_range returns 199999 | |
# use_range_local returns 199999 | |
# use_zip returns 199999 | |
# use_range: 10.198090834077448 | |
# use_range_local: 8.507670041057281 | |
# use_zip: 6.672960666939616 | |
import timeit | |
a = list(range(1, 100001)) | |
def use_range(): | |
s = 0 | |
for i in range(1, len(a)): | |
s += a[i] - a[i-1] + a[i] // a[i-1] | |
return s | |
def use_range_local(): | |
s = 0 | |
for i in range(1, len(a)): | |
x, y = a[i-1], a[i] | |
s += y - x + y // x | |
return s | |
def use_zip(): | |
s = 0 | |
for x, y in zip(a, a[1:]): | |
s += y - x + y // x | |
return s | |
print(f'use_range returns {use_range()}') | |
print(f'use_range_local returns {use_range_local()}') | |
print(f'use_zip returns {use_zip()}') | |
print(f'use_range: {timeit.timeit("use_range()", globals=locals(), number=1000)}') | |
print(f'use_range_local: {timeit.timeit("use_range_local()", globals=locals(), number=1000)}') | |
print(f'zip: {timeit.timeit("use_zip()", globals=locals(), number=1000)}') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment