Created
February 14, 2012 17:22
-
-
Save haldean/1828270 to your computer and use it in GitHub Desktop.
Test "while 1" vs. "while True" in Python
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
# Testing results (lower number is faster): | |
# while True while 1 | |
# pypy 1.7.0: 0.0733 0.0201 | |
# cpython 2.7.1 0.146 0.109 | |
# cpython 3.2.2 2.79 2.72 | |
loops = 10000 | |
trials = 1000 | |
def while_True(): | |
x = 0 | |
while True: | |
x += 1 | |
if x > loops: | |
break | |
def while_1(): | |
x = 0 | |
while 1: | |
x += 1 | |
if x > loops: | |
break | |
import timeit | |
print('while True: ', timeit.timeit(while_True, number=trials)) | |
print('while 1: ', timeit.timeit(while_1, number=trials)) |
Turns out in Python 2, you can redefine True, so it has to do a lookup in the global namespace every time. In Python 3, True becomes a reserved word so it doesn't have to do the lookup. Thanks, /r/Python
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good to know.