Skip to content

Instantly share code, notes, and snippets.

@calebmadrigal
Last active September 24, 2015 15:48
Show Gist options
  • Save calebmadrigal/d80a0bf1bed650b4a035 to your computer and use it in GitHub Desktop.
Save calebmadrigal/d80a0bf1bed650b4a035 to your computer and use it in GitHub Desktop.
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