Skip to content

Instantly share code, notes, and snippets.

@calebmadrigal calebmadrigal/for_loop.py
Last active Sep 24, 2015

Embed
What would you like to do?
Python for loop vs list comprehension speed test. This is just testing the speed of performing a particular operation in both a for loop and list comprehension. Note that the list comprehension version uses more memory because it is storing the results. This could be partially responsible for it being slower.
import sys
num = int(sys.argv[1])
def test(i):
return i+1
for i in range(num):
t = test(i)
import sys
num = int(sys.argv[1])
def test(i):
return i+1
[test(i) for i in range(num)]
cmadrigal-MBP:python-loop-test caleb.madrigal$ time python3 list_comp.py 50000000
real 0m10.099s
user 0m8.602s
sys 0m1.484s
cmadrigal-MBP:python-loop-test caleb.madrigal$ time python3 for_loop.py 50000000
real 0m9.281s
user 0m9.227s
sys 0m0.014s
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.