2011年5月3日火曜日

[Python] while True と while 1

while True と while 1 では結構性能が違う。

Python 2.7.1 on win32
>>> import timeit
>>>
>>> stmt1 = """
... i = 0
... while True:
...     i += 1
...     if i > 100:
...             break
... """
>>> stmt2 = """
... i = 0
... while 1:
...     i += 1
...     if i > 100:
...             break
... """
>>> t1 = timeit.Timer(stmt = stmt1)
>>> t2 = timeit.Timer(stmt = stmt2)
>>> t1.timeit()
8.104886514906184
>>> t2.timeit()
5.19364556109781
>>>

while 1 のほうが速い。