Why is 2 * x * x faster than 2 * ( x * x ) in Python 3.x, for integers?

前端 未结 4 700
我在风中等你
我在风中等你 2021-01-30 13:37

The following Python 3.x integer multiplication takes on average between 1.66s and 1.77s:

import time
start_time = time.time()
num = 0
for x in range(0, 10000000         


        
4条回答
  •  生来不讨喜
    2021-01-30 13:55

    Python intern representation of integers is special, it uses slots of 30 bits :

    In [6]: sys.getsizeof(2**30-1)
    Out[6]: 28 # one slot + heading
    
    In [7]: sys.getsizeof(2**30)
    Out[7]: 32 # two slots 
    

    So everything happens as if Python counts in base B = 2**30 = 1 073 741 824 ~1 billion.

    For a human who want to calculate 2*4*4, two ways :

    • (2*4)*4 = 8*4 =32 = 30 + 2 is immediate if you knows your add tables.
    • 2*(4*4) = 2*16 = 2*10 + 2*6 = (2*10+10) + 2 = 30 + 2 since we have to put the operation down.

    Python have the same problem. If x is a number such than 2x < B < x² , let x² = aB+b , with a,b . is stored in 2 slots, which I note (a|b). Computations leads to (without managing carries here):

       (x*x)*2 =>  (a|b)*2 => (2*a|2*b)
       (2*x)*x =>  (2x)*x =>(2a|2b)
    

    in the first case the 2* operation is done two times, against only one in the first case. That explains the difference.

提交回复
热议问题