why does dead code costs time?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Dec 5 12:34:57 EST 2012


On Wed, 05 Dec 2012 16:46:39 +0100, Bruno Dupuis wrote:

> Hi,
> 
> I'm interested in compilers optimizations, so I study python compilation
> process
> 
> I ran that script:
> 
>     import timeit
> 
>     def f(x):
>         return None
> 
>     def g(x):
>         return None
>         print(x)
> 
>     number = 10000
> 
>     print(timeit.timeit('f(1)',setup="from __main__ import f",
>     number=number)) print(timeit.timeit('g(1)',setup="from __main__
>     import g", number=number))
> 
>     print(dis.dis(f))
>     print(dis.dis(g))
> 
> It gives this output:
> 
>     0.003460251959040761
>     0.004164454061537981
>      17           0 LOAD_CONST               0 (None)
>                   3 RETURN_VALUE
>     None
>      20           0 LOAD_GLOBAL              0 (None)
>                   3 RETURN_VALUE
> 
>      21           4 LOAD_GLOBAL              1 (print)
>                   7 LOAD_FAST                0 (x)
>                  10 CALL_FUNCTION            1 (1 positional, 0 keyword
>                  pair) 13 POP_TOP
>     None
> 
> I do not understand why the dead code `print(x)` takes time (~20% in
> that case). As we see in the opcode, a call to g(1) returns immediately,
> so there should be no delay at all. Where am i wrong?

The difference is almost certain between the LOAD_CONST and the 
LOAD_GLOBAL.

As to *why* there is such a difference, I believe that's a leftover from 
early Python days when None was not a keyword and could be reassigned.


[steve at ando ~]$ python1.5
Python 1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 (Red Hat 
4.1.2-52)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> from dis import dis
>>>
>>> def h():
...     x = 1
...     return None
...
>>> dis(h)
          0 SET_LINENO          1

          3 SET_LINENO          2
          6 LOAD_CONST          1 (1)
          9 STORE_FAST          0 (x)

         12 SET_LINENO          3
         15 LOAD_GLOBAL         1 (None)
         18 RETURN_VALUE
         19 LOAD_CONST          0 (None)
         22 RETURN_VALUE
>>> None = 42
>>> h()
42


Now that None is a keyword, it should always be a LOAD_CONST.


-- 
Steven



More information about the Python-list mailing list