Python 中哪个更快:x**.5 或 math.sqrt(x)? [英] Which is faster in Python: x**.5 or math.sqrt(x)?

查看:68
本文介绍了Python 中哪个更快:x**.5 或 math.sqrt(x)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

更新

这不是过早优化的问题.这只是底层代码如何实际工作的问题.Python 代码的工作原理是什么?

我给 Guido van Rossum 发了一封电子邮件,因为我真的很想知道这些方法的区别.

我的电子邮件:

<块引用>

在 Python 中至少有 3 种方法可以做平方根:math.sqrt,'**' 运算符和 pow(x,.5).我只是好奇每一个的实施.当谈到效率时更好吗?

他的回应:

<块引用>

pow 和 ** 是等价的;math.sqrt 不适用于复数,并链接到 C sqrt() 函数.至于哪个是更快,我不知道...

解决方案

math.sqrt(x) 明显快于 x**0.5.

导入数学N = 1000000

%%timeit对于范围(N)中的我:z=i**.5

<块引用>

10 个循环,最好的 3 个:每个循环 156 毫秒

%%timeit对于范围(N)中的我:z=math.sqrt(i)

<块引用>

10 个循环,最好的 3 个:每个循环 91.1 毫秒

使用 Python 3.6.9(笔记本).

I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?

UPDATE

This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?

I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.

My email:

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?

His response:

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) is significantly faster than 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

Using Python 3.6.9 (notebook).

这篇关于Python 中哪个更快:x**.5 或 math.sqrt(x)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆