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

前端 未结 4 702
我在风中等你
我在风中等你 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:44

    From what I can tell, it comes down to a little bit more memory access in the version using 2 * (x * x). I printed the disassembled bytecode and it seems to prove that:

    Relevant part of 2 * x * x:

    7          28 LOAD_FAST                1 (num)
               30 LOAD_CONST               3 (2)
               32 LOAD_FAST                2 (x)
               34 BINARY_MULTIPLY
               36 LOAD_FAST                2 (x)
               38 BINARY_MULTIPLY
               40 INPLACE_ADD
               42 STORE_FAST               1 (num)
               44 JUMP_ABSOLUTE           24
    

    Relevant part of 2 * (x * x):

      7          28 LOAD_FAST                1 (num)
                 30 LOAD_CONST               3 (2)
                 32 LOAD_FAST                2 (x)
                 34 LOAD_FAST                2 (x)
                 36 BINARY_MULTIPLY                 <=== 1st multiply x*x in a temp value
                 38 BINARY_MULTIPLY                 <=== then multiply result with 2
                 40 INPLACE_ADD
                 42 STORE_FAST               1 (num)
                 44 JUMP_ABSOLUTE           24
    

提交回复
热议问题