Hello! I just made a Stack Exchange profile to participate in this conversation!
What I am doing might seem trivial, but hear me out once before judging:
Experiment Conditions:
- Offline(no internet compiler issues)
- Keeping my system state as stable as possible
- In one attempt testing all 3 functions
I ran 3 loops of 5 iterations each, for each function stated in the original question. And I calculated the square root for Integers from 0 to 10^8 in each loop.
Here are the results:
Time Taken:
sqrt(x)
< x**0.5
< pow(x, 0.5)
Note: By a margin of double-digit seconds, over 10^8 non-negative
integers.
Screenshot of outputs:
Outputs
My Conclusion:
I feel Guido's email justifies these timings well.
Consider the following statements:
- "
math.sqrt()
links to C and does not entertain complex numbers"
- "
**
and pow()
are equivalent"
We can thus imply that **
and pow()
both have certain overhead costs since they both have to check in case the input passed is a complex number, even if we pass an integer. Moreover, Complex Numbers are built-ins for Python, and using Python to write Python code is tasking on the computer.
And very notably, math.sqrt()
works relatively faster because neither does it have to go through the trouble of checking for Complex Number arguments, but also because it is directly connected with the C language function, which are proven to be a little faster than Python in general.
Let me know in case your opinion differs from mine in this conclusion!
Code:
import time
import math
print("x**0.5 : ")
for _ in range(5):
start = time.time()
for i in range(int(1e8)):
i**0.5
end = time.time()
print(end-start)
print("math.sqrt(x) : ")
for _ in range(5):
start = time.time()
for i in range(int(1e8)):
math.sqrt(i)
end = time.time()
print(end-start)
print("pow(x,0.5) : ")
for _ in range(5):
start = time.time()
for i in range(int(1e8)):
pow(i,0.5)
end = time.time()
print(end-start)
sqrt = lambda n: n**0.5
, when that's faster and also works for complex numbers like guido said. – Bertrandomath.sqrt
is a more optimized routine (as it is) and expresses the intent more clearly, it should always be preferred overx**.5
. It is not premature optimization to know what you write, and chose the alternative that is faster and provides more code clarity. If so, you need to argue equally well why you would chose the other alternatives. – Yager