The two multiplications, 2*i*i
and 2*(i*i)
, are equal and should generate the same result, which only changes is the order that the multiplications are made, but apparently they are treated differently by the interpreter. >
In the first multiplication, given the absence of parentheses and considering that all operations have the same precedence , the interpreter will execute from left to right; that is, first it will be done 2*i
and the result multiplied by i
.
In the second multiplication, given the presence of the parentheses, the order of execution is changed because the i*i
multiplication takes precedence over multiplication by 2, then the first interpreter will i*i
and the result will multiply by 2 .
Mathematically, the order of the factors does not change the product, so the result should be the same, however using the native package timeit
you can see a difference between the runtimes between these multiplications:
>>> print('2*i*i:', timeit("for i in range(1000): 2*i*i"))
2*i*i: 276.91411599100684
>>> print('2*(i*i):', timeit("for i in range(1000): 2*(i*i)"))
2*(i*i): 279.21798045100877
Tests were done at Repl.it
Note: It is important to note that the
timeit
function will, by default, execute the specified code snippet 1,000,000 times, and that the exact execution time may vary due to processor oscillations and between computers.
Why is there such a time difference? Does the presence of the parentheses in the expression change the executed algorithm?
Emphasizing that the analysis should be done in the official implementation of Python, CPython, in version 3+. Comparisons with other versions or implementations will be welcomed as a way to increase response.