why does dead code costs time?

Ramchandra Apte maniandram01 at gmail.com
Sun Dec 9 15:11:07 CET 2012


On Wednesday, 5 December 2012 22:10:51 UTC+5:30, Bruno Dupuis  wrote:
> On Wed, Dec 05, 2012 at 04:15:59PM +0000, Neil Cerutti wrote:
> 
> > On 2012-12-05, Bruno Dupuis <python.ml.bruno.dupuis at lisael.org> 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?
> 
> > >
> 
> > > mmhh... it comes to me now that the gap must be in function loading time...
> 
> > > I'll check ceval.c
> 
> > >
> 
> > > However, isn't there a room for a slight optim here? (in this case, the
> 
> > > dead code is obvious, but it may be hidden by complex loops and
> 
> > > conditions)
> 
> > 
> 
> > Maybe it's the difference between LOAD_CONST and LOAD_GLOBAL. We
> 
> > can wonder why g uses the latter.
> 
> 
> 
> Good point! I didn't even noticed that. It's weird... Maybe the
> 
> difference comes from a peehole optim on f which is not possible on g as
> 
> g is to complex.
> 
> 
> 
> > 
> 
> > -- 
> 
> > Neil Cerutti
> 
> > -- 
> 
> > http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
> -- 
> 
> Bruno Dupuis

peehole haha



More information about the Python-list mailing list