Simple question about how the optimizer works

François Pinard pinard at iro.umontreal.ca
Thu May 9 09:00:33 EDT 2002


[jb]

> > How often is then f called in the following code:
> > 
> > print g(f(x),f(x))
> > print h(f(x),f(x))
> > 
> > I think this topic is called "common subexppression elimination" in
> > computer science.

> [...] I have tried and I am a bit surprised that f is called four times!
> Why?

Python does not really optimise the code it generates.  Some brave souls
(Skip in particular) did flurries of tries in that direction, and kind of
demonstrated that byte-code optimisations might not be as rewarding as we
could have thought it would be.

In the particular case above, CSE may not be applied, because the optimiser,
if it existed, could not assume that `f' has no side-effect.  Suppose:

    def f(x):
        global y
        y = y + 1
        return x + y

then `y' should be incremented four times, not one.  Moreover, I do not
remember that Python specifies that function arguments are evaluated left
to right, or right to left.  But I may be wrong, I'm not sure.  If the
order is unspecified, and `f' does not always return the same value for
the same argument, the code in the original message would not even be
sensible Python, because it would yield unpredictable results.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list