Skip to content

Instantly share code, notes, and snippets.

@coderfi
Created August 3, 2014 19:01
Show Gist options
  • Save coderfi/1b263141e2defb071c96 to your computer and use it in GitHub Desktop.
Save coderfi/1b263141e2defb071c96 to your computer and use it in GitHub Desktop.
See the timing difference between using for loops and itertools
from itertools import ifilter
import sys
import timeit
REPEAT = 3
EXECUTIONS = 10000
VALUES = range(0, 10000)
def double(x):
return x*2
def with_loop(values,):
for x in values:
x = double(x)
def with_itertools(values):
for x in values:
_ = x
if __name__ == '__main__':
print "\n=== timeit tests REPEAT={0} EXECUTIONS={1} TOTAL={2} ===".format(
REPEAT, EXECUTIONS, REPEAT*EXECUTIONS)
t = timeit.repeat('with_loop(VALUES)',
setup="from __main__ import"
" double, with_loop, VALUES",
repeat=REPEAT,
number=EXECUTIONS)
print "with_loop: avg = %.8f" % (sum(t)/len(t))
t = timeit.repeat('with_itertools(ifilter(double, VALUES))',
setup="from __main__ import"
" double, with_itertools, VALUES, ifilter",
repeat=REPEAT,
number=EXECUTIONS)
print "with_itertools: avg = %.8f" % (sum(t)/len(t))
@coderfi
Copy link
Author

coderfi commented Aug 3, 2014

=== timeit tests REPEAT=3 EXECUTIONS=10000 TOTAL=30000 ===
with_loop: avg = 9.94407606
with_itertools: avg = 12.94683170

Interesting that itertools adds a 30% overhead?!

Note: Python 2.7.6 on MacBook PRO

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