performance of tight loop

Ryan Kelly ryan at rfk.id.au
Tue Dec 14 02:56:21 EST 2010


On Tue, 2010-12-14 at 08:08 +0100, Ulrich Eckhardt wrote:
> Steven D'Aprano wrote:
> > Replacing "while True" with "while 1" may save a tiny bit of overhead.
> > Whether it is significant or not is another thing.
> 
> Is this the price for an intentional complexity or just a well-known
> optimizer deficiency?

At least on older pythons, you can assign to the name "True" so it's not
possible to optimize that loop - you must look up the name "True" on
each iteration.  For example, in python 2.6 this loop will exit after
one iteration:


    >>> while True:
    ...     True = False
    ...
    >>>

To see the difference, take a look at the bytecode python generators for
the type types of loop:


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

      3     >>    3 JUMP_ABSOLUTE            3
            >>    6 LOAD_CONST               0 (None)
                  9 RETURN_VALUE        
    >>>
    >>> 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        
   >>> 


Still, I just can't bring myself to write "while 1" in favour of "while
True" in code.


Python 3 does away with this madness entirely:


    >>> while True:
    ...     True = False
    ... 
      File "<stdin>", line 2
    SyntaxError: assignment to keyword
    >>> 

Looking at the bytecode shows that in Python 3, "while 1" and "while
True" are indeed identical.


  Cheers,

     Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/python-list/attachments/20101214/726030a7/attachment-0001.sig>


More information about the Python-list mailing list