Created
February 16, 2014 02:07
-
-
Save AphonicChaos/9028268 to your computer and use it in GitHub Desktop.
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
| from timeit import timeit | |
| children = range(1, 1000) | |
| number = 10000 | |
| def indexof(x): | |
| for i in range(len(children)): | |
| if children[i] is x: | |
| return i | |
| return -1 | |
| def index(x): | |
| try: | |
| return children.index(x) | |
| except ValueError: | |
| return -1 | |
| if __name__ == '__main__': | |
| print("indexof(200) = {}\nindexof(2000) = {}\n".format( | |
| indexof(200), indexof(2000))) | |
| print("result of calling {} times:".format(number)) | |
| print(timeit( | |
| "indexof(200); indexof(2000)", | |
| number=number, | |
| setup="from __main__ import indexof")) | |
| print("index(200) = {}\nindex(2000) = {}\n".format( | |
| indexof(200), indexof(2000))) | |
| print("result of calling {} times:".format(number)) | |
| print(timeit( | |
| "index(200); index(2000)", | |
| number=number, | |
| setup="from __main__ import index")) | |
| """ Results: | |
| Python 2: | |
| indexof(200) = 199 | |
| indexof(2000) = -1 | |
| result of calling 10000 times: | |
| 0.784973859787 | |
| index(200) = 199 | |
| index(2000) = -1 | |
| result of calling 10000 times: | |
| 0.238559007645 | |
| Python 3: | |
| indexof(200) = 199 | |
| indexof(2000) = -1 | |
| result of calling 10000 times: | |
| 2.492364877994987 | |
| index(200) = 199 | |
| index(2000) = -1 | |
| result of calling 10000 times: | |
| 0.015736084009404294 | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment