我一直在想这个问题。正如标题所说,哪个更快,实际功能还是简单地提高到一半?
更新
这不是过早优化的问题。这只是底层代码如何实际工作的问题。 Python 代码的工作原理是什么?
我给 Guido van Rossum 发了一封电子邮件,因为我真的很想知道这些方法的区别。
There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?
pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...
最佳答案
math.sqrt(x)
明显快于 x**0.5
。
import math
N = 1000000
%%timeit
for i in range(N):
z=i**.5
10 loops, best of 3: 156 ms per loop
%%timeit
for i in range(N):
z=math.sqrt(i)
10 loops, best of 3: 91.1 ms per loop
使用 Python 3.6.9 (notebook)。
https://stackoverflow.com/questions/327002/