Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A more robust approach to testing the findings at http://rickystewart.wordpress.com/2013/09/03/why-sorting-an-array-makes-a-python-loop-faster/ that factors out all the "buts" that immediately came to mind.
import timeit
sorted_setup = """
a = range(1000000)
"""
unsorted_setup = """
from random import shuffle
{}
shuffle(a)
""".format(sorted_setup)
forloop_stmt = """
for i in a:
pass
"""
comprehension_stmt = """
[i for i in a]
"""
print "Checking timings."
# How many times to run the statement.
n = 1000
# For loop
t_sorted_forloop = timeit.timeit(forloop_stmt, sorted_setup, number=n)
t_unsorted_forloop = timeit.timeit(forloop_stmt, unsorted_setup, number=n)
# List comprehension
t_sorted_comprehension = timeit.timeit(comprehension_stmt, sorted_setup, number=n)
t_unsorted_comprehension = timeit.timeit(comprehension_stmt, unsorted_setup, number=n)
print "Sorted for loop:"
print t_sorted_forloop
print
print "Unsorted for loop:"
print t_unsorted_forloop
print
print "Sorted comprehension:"
print t_sorted_comprehension
print
print "Unsorted comprehension:"
print t_unsorted_comprehension
print
Results from running this on my Mac, OS X 10.6.8, 2.7GHz Intel Core i7 yadda yadda:
Sorted for loop:
18.2923810482
Unsorted for loop:
56.756278038
Sorted comprehension:
124.576835871
Unsorted comprehension:
126.68524313
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.