Last active
September 24, 2015 15:48
-
-
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.
This file contains 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 sys | |
num = int(sys.argv[1]) | |
def test(i): | |
return i+1 | |
for i in range(num): | |
t = test(i) |
This file contains 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 sys | |
num = int(sys.argv[1]) | |
def test(i): | |
return i+1 | |
[test(i) for i in range(num)] |
This file contains 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
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