python - 在 Python : x**. 5 或 math.sqrt(x) 中哪个更快?

我一直在想这个问题。正如标题所说,哪个更快,实际功能还是简单地提高到一半?

更新

这不是过早优化的问题。这只是底层代码如何实际工作的问题。 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/

相关文章:

python - 如何在 Python 请求中禁用安全证书检查

linux - 大量文件的快速 Linux 文件计数

linux - Bash循环中的计数器增量不起作用

python - 如何从 Visual Studio Code 中执行 Python 代码

python - 在 python shell 中按箭头键时看到转义字符

python - python,del或delattr哪个更好?

python - 我在 python 中遇到关键错误

linux - 使用 awk 保存修改

python - 递归删除python中的文件夹

linux - 仅在尚未运行时运行 cron 作业