Last active
December 22, 2015 09:39
-
-
Save eykd/6453378 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or 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 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 "Unsorted for loop:" | |
| print t_unsorted_forloop | |
| print "Sorted comprehension:" | |
| print t_sorted_comprehension | |
| print "Unsorted comprehension:" | |
| print t_unsorted_comprehension | |
This file contains hidden or 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
| 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