Last active
July 15, 2016 15:20
-
-
Save felipeblassioli/5c28ae56e4a0db14f8993962772f300a to your computer and use it in GitHub Desktop.
Python 2.7 itertools.product vs nested for loops vs nested for comprehension
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
import timeit | |
def test_performance(code, setup='pass', TIMES=10): | |
avg = lambda l: sum(l)/len(l) | |
result = timeit.Timer(code, setup).repeat(3,10) | |
print avg(result) | |
NESTED_FOR = """ | |
for x in xrange(1000): | |
for y in xrange(1000): | |
pass | |
""" | |
test_performance(NESTED_FOR) | |
NESTED_COMPREHENSION = """ | |
for x,y in [ (x,y) for x in xrange(2500) for y in xrange(2500) ]: | |
pass | |
""" | |
test_performance(NESTED_COMPREHENSION) | |
SETUP = """from itertools import product""" | |
ITERTOOLS_PRODUCT_1 = """ | |
for x, y in product(xrange(1000), repeat=2): | |
pass | |
""" | |
test_performance(ITERTOOLS_PRODUCT_1, setup=SETUP) | |
SETUP = """from itertools import product""" | |
ITERTOOLS_PRODUCT_2 = """ | |
for x, y in product(xrange(1000), xrange(1000)): | |
pass | |
""" | |
test_performance(ITERTOOLS_PRODUCT_2, setup=SETUP) | |
# RESULTS | |
# 0.127683003743 | |
# 8.17029802004 | |
# 0.268307367961 | |
# 0.262320359548 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/python/cpython/blob/2.7/Modules/itertoolsmodule.c -> Implementation of product