I was wondering whether x**2 or x*x is faster
def sqr(x):
for i in range (20):
x = x**2
return x
def sqr_(x):
for i in range (20):
x = x*x
return x
When I time it, this is what I get:
The time it takes for x**2: 101230500
The time it takes for x*x: 201469200
I have tried it many many times, they are either equal, or x ** 2 is faster than x * x. But x*x is never faster than x**2.
So I dissembled the code:
For x**2:
5 12 LOAD_FAST 0 (x)
14 LOAD_CONST 2 (2)
16 BINARY_POWER
18 STORE_FAST 0 (x)
20 JUMP_ABSOLUTE 8
For x*x:
9 12 LOAD_FAST 0 (x)
14 LOAD_FAST 0 (x)
16 BINARY_MULTIPLY
18 STORE_FAST 0 (x)
20 JUMP_ABSOLUTE 8
Is it about load_const being slightly faster than load_fast?
LOAD_CONST: takes the literal value at index 1 of co_consts and pushes it
LOAD_FAST is accessing the value in an array by index
Or binary_power is faster than binary_multiply (I actually don't know the binary_power algorithm)?