Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save felipeblassioli/5c28ae56e4a0db14f8993962772f300a to your computer and use it in GitHub Desktop.
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
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
@felipeblassioli
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment