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

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

    If your benchmark is right (didn't check), it may come from the fact that Python integers may be two different things : native integers when they are small (with a quick computation), and big integers when they increase in size (slower computation). The first syntax keeps the size smaller after the first operation while the second syntax may lead to two operations involving big integers.

提交回复
热议问题