while True or while 1

Christian Heimes lists at cheimes.de
Sun Dec 12 14:32:00 EST 2010


Am 12.12.2010 19:31, schrieb Steve Holden:
> Would you care to quantify how much CPU time that optimization will
> typically save for a loop of fair magnitude (say, a billion iterations)?

The difference is minimal but measurable for very tight loops.

$ python -m timeit -n20 -- "i = 0" "while 1:" "    i+=1" "    if i ==
1000000: break"
20 loops, best of 3: 89.7 msec per loop
$ python -m timeit -n20 -- "i = 0" "while True:" "    i+=1" "    if i ==
1000000: break"
20 loops, best of 3: 117 msec per loop

In Python 2.x the peep hole optimizer can't remove the global lookup and
check for trueness for "while True".

>>> def while1():
...     while 1:
...         pass
...
>>> import dis
>>> dis.dis(while1)
  2           0 SETUP_LOOP               3 (to 6)

  3     >>    3 JUMP_ABSOLUTE            3
        >>    6 LOAD_CONST               0 (None)
              9 RETURN_VALUE
>>> def whiletrue():
...     while True:
...         pass
...
>>> dis.dis(whiletrue)
  2           0 SETUP_LOOP              12 (to 15)
        >>    3 LOAD_GLOBAL              0 (True)
              6 JUMP_IF_FALSE            4 (to 13)
              9 POP_TOP

  3          10 JUMP_ABSOLUTE            3
        >>   13 POP_TOP
             14 POP_BLOCK
        >>   15 LOAD_CONST               0 (None)
             18 RETURN_VALUE

> Python is designed to provide readable code. Writing
> 
>     while True:
>         ...
> 
> is much more legible than its pre-True couterpart
> 
>     while 1:
>         ...

No argue with that! I was merely making a point that "while 1" executes
different byte code than "while True". Readability is important but
sometimes speed is of the essence. "while 1" is one of the few tricks to
speed up tight loops a bit.

Christian




More information about the Python-list mailing list