Skip to content

Instantly share code, notes, and snippets.

@haldean
Created February 14, 2012 17:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save haldean/1828270 to your computer and use it in GitHub Desktop.
Save haldean/1828270 to your computer and use it in GitHub Desktop.
Test "while 1" vs. "while True" in Python
# 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))
@mosesn
Copy link

mosesn commented Feb 14, 2012

good to know.

@haldean
Copy link
Author

haldean commented Feb 14, 2012

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