Multiplication optimization

Peter Otten __peter__ at web.de
Mon Feb 20 03:07:32 EST 2006


Atanas Banov wrote:

> Paul McGuire wrote:
>> Does Python's run-time do any optimization of multiplication
>> operations, like it does for boolean short-cutting?  That is, for a
>> product a*b, is there any shortcutting of (potentially expensive)
>> multiplication operations
> 
> no. and the reason is very simple: to the extent such optimization
> makes sense, it has been done on assembler/CPU level already. i.e. when
> the multiplication is mapped to the machine code
>    IMUL  <op>
> the Pentium processor would be smart enough not to do the work if AX or
> the op are 0 or 1.
> 
> Python has no job trying to outsmart Intel (and the other chipmakers).
> Boolean shortcuts are useful for entirely different reason, not speed.
> e.g.
>         if lastDigit == 0 or i % lastDigit != 0:
>             break
> 
> if both operands of OR were to be evaluated, that would end up with
> division-by-zero exception for lastDigit=0.

The point is not to avoid the multiplication on the CPU level but the object
creation overhead:

>>> a = 1234
>>> 1 * a is a
False # could be True


$ python -m timeit -s'a=1;b=1234567' 'if a is 1: x = b' 'else: x = a * b'
10000000 loops, best of 3: 0.171 usec per loop
$ python -m timeit -s'a=1;b=1234567' 'x = a * b'
1000000 loops, best of 3: 0.211 usec per loop
$ python -m timeit -s'a=2;b=1234567' 'if a is 1: x = b' 'else: x = a * b'
1000000 loops, best of 3: 0.329 usec per loop

If 'a is 1' is sufficiently likely, that test speeds up the code even in
pure Python. Of course a generalized implementation would also have to
check b's type:

$ python -m timeit -s'a=1;b=1234567' 'if a is 1 and b.__class__ is int: x =
b' 'else: x = a * b'
1000000 loops, best of 3: 0.484 usec per loop

So that is not a good idea, at least in pure Python.

Peter




More information about the Python-list mailing list