Multiplication optimization

Raymond Hettinger python at rcn.com
Sat Feb 18 21:55:22 EST 2006


[Paul McGuire]
> Does Python's run-time do any optimization of multiplication
> operations, like it does for boolean short-cutting?

Usually, it is safest (and typically true) to assume that Python
performs no optimizations.  To go beyond making assumptions, it is easy
to run a few timings:

>>> from timeit import Timer
>>> min(Timer('0*1234567').repeat(5))
0.11315376674968469
>>> min(Timer('1*1234567').repeat(5))
0.11920453577200618
>>> min(Timer('113*1234567').repeat(5))
0.11881482143680699

In your specific case, I can answer than the source shows no special
optimization for multiplications by specific values.  There is a
short-path for integer multiplications but it is not value specific.
In Py2.5, the compiler will do a limited amount of constant folding;
however, its scope is somewhat limited because expressions like a*3
vary depending on the a's type which is often not knowable by the
compiler without some form of global analysis.

One other thought:  Python is not assembly.  Run time is unlikely to be
dominated by the time to execute a multiplication.  With Python, it is
best to focus optimization efforts on making choosing the best data
structures and hoisting constants out of loops.


Raymond




More information about the Python-list mailing list