Array of 2^n

Skip Montanaro skip at pobox.com
Tue Oct 23 15:15:01 CEST 2001


    Andreas> Well, at least for python 2.0 (SuSE 7.2) this way [list
    Andreas> comprehensions] is also about 25% slower than map/lambda...
    Andreas> Has it been sped up in later versions?

Not significantly.  List comprehensions are byte compiled to almost the same
code that you would get with the obvious for loop translation.  Map(), on
the other hand, is a function, so it gets compiled to a function call
opcode.  That means the loop machinery runs in C instead of in the Python
virtual machine.

The Python disassembler is instructive here, and so simple to use, everyone
ought to be familiar with it, even if just to answer these sorts of
questions.  Here's how:

1. Define a function which contains the construct you're interested in
   examining:

    def foo(n):
        return [i**2 for i in range(n)]

2. Invoke the python interpreter with the -O flag (avoids those pesky
   SET_LINENO instructions in the output).

3. Import both the module containing your function and the dis module:

    >>> import foo, dis

4. Disassemble the function:

    >>> dis.dis(foo.foo)
              0 BUILD_LIST               0
              3 DUP_TOP             
              4 LOAD_ATTR                0 (append)
              7 STORE_FAST               1 (_[1])
             10 LOAD_GLOBAL              2 (range)
             13 LOAD_FAST                0 (n)
             16 CALL_FUNCTION            1
             19 GET_ITER            
        >>   20 FOR_ITER                20 (to 43)
             23 STORE_FAST               2 (i)
             26 LOAD_FAST                1 (_[1])
             29 LOAD_FAST                2 (i)
             32 LOAD_CONST               1 (2)
             35 BINARY_POWER        
             36 CALL_FUNCTION            1
             39 POP_TOP             
             40 JUMP_ABSOLUTE           20
        >>   43 DELETE_FAST              1 (_[1])
             46 RETURN_VALUE        
             47 LOAD_CONST               0 (None)
             50 RETURN_VALUE        

repeat-as-necessary-ly, y'rs,

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list