Reputation: 393
I am practising the fast power algorithm in Python3, and I tested it against Python's built-in power function.
Why it turns out the built-in function is so much faster?
My code:
def levinPOW(n, k):
res = 1
while k:
if k&1:
res *= n
n *= n
k = k >> 1
return res
import time
start = time.time()
a = levinPOW(2, 10000000)
end = time.time()
print(end-start)
start = time.time()
b = 2 ** 10000000
end = time.time()
print(end-start)
print(a==b)
Result:
0.31336236000061035
4.291534423828125e-06
True
Upvotes: 1
Views: 168
Reputation: 5184
The builtin is implemented in C which is much faster than implementing it in Python. It's also probably had several people making speed improvements to it.
Upvotes: 1