gpt4 book ai didi

python - 为什么 2**100 比 math.pow(2,100) 快这么多?

转载 作者:太空狗 更新时间:2023-10-29 21:39:42 24 4
gpt4 key购买 nike

讨论问题时Exponentials in python x.**y vs math.pow(x, y) , Alfe stated没有充分的理由使用 math.pow 而不是 python 中的内置 ** 运算符。

timeit shows that math.pow is slower than ** in all cases. What is math.pow() good for anyway? Has anybody an idea where it can be of any advantage then?

我们试图用一些 timeit 参数说服对方,到目前为止他是赢家 ;-) -- 至少以下 timeit 结果似乎证实了这一点math.pow 在所有情况下都比 ** 慢

import timeit
print timeit.timeit("math.pow(2, 100)",setup='import math')
print timeit.timeit("2.0 ** 100.0")
print timeit.timeit("2 ** 100")
print timeit.timeit("2.01 ** 100.01")

输出:

0.329639911652
0.0361258983612
0.0364260673523
0.0363788604736

( ideone-shortcut )

我们观察到的差异[1]是否有简单的解释?


[1] math.pow** 的性能相差一个数量级。

编辑:

  • 文字参数而不是标题中的变量
  • 明确指出差异幅度的脚注

最佳答案

本质上,幂运算符在您的示例中表现出色的原因是因为 Python 很可能有 folded the constant在编译时。

import dis
dis.dis('3.0 ** 100')
i = 100
dis.dis('3.0 ** i')

这给出了以下输出:

  1           0 LOAD_CONST               2 (5.153775207320113e+47)
3 RETURN_VALUE
1 0 LOAD_CONST 0 (3.0)
3 LOAD_NAME 0 (i)
6 BINARY_POWER
7 RETURN_VALUE

您可以在此处看到此运行:http://ideone.com/5Ari8o

所以在这种情况下,您可以看到它实际上并没有对幂运算符与 math.pow 的性能进行公平比较,因为结果已预先计算然后缓存。当您制作 3.0 ** 100 时,没有执行任何计算,只是返回结果。这比在运行时执行的任何求幂运算都要快得多。这最终解释了您的结果。

为了更公平的比较,您需要使用变量强制在运行时进行计算:

print timeit.timeit("3.0 ** i", setup='i=100')

我尝试在我的计算机上使用 python 3.4.1 对此进行快速基准测试:

import timeit
trials = 1000000
print("Integer exponent:")
print("pow(2, 100)")
print(timeit.timeit(stmt="pow(2, 100)", number=trials))
print("math.pow(2, 100)")
print(timeit.timeit(stmt="m_pow(2, 100)", setup='import math; m_pow=math.pow', number=trials))
print("2 ** 100")
print(timeit.timeit(stmt="2 ** i", setup='i=100', number=trials))
print("2.0 ** 100")
print(timeit.timeit(stmt="2.0 ** i", setup='i=100', number=trials))
print("Float exponent:")
print("pow(2.0, 100.0)")
print(timeit.timeit(stmt="pow(2.0, 100.0)", number=trials))
print("math.pow(2, 100.0)")
print(timeit.timeit(stmt="m_pow(2, 100.0)", setup='import math; m_pow=math.pow', number=trials))
print("2.0 ** 100.0")
print(timeit.timeit(stmt="2.0 ** i", setup='i=100.0', number=trials))
print("2.01 ** 100.01")
print(timeit.timeit(stmt="2.01 ** i", setup='i=100.01', number=trials))

结果:

Integer exponent:
pow(2, 100)
0.7596459520525322
math.pow(2, 100)
0.5203307256717318
2 ** 100
0.7334983742808263
2.0 ** 100
0.30665244505310607
Float exponent:
pow(2.0, 100.0)
0.26179656874310275
math.pow(2, 100.0)
0.34543158098034743
2.0 ** 100.0
0.1768205988074767
2.01 ** 100.01
0.18460920008178894

所以看起来转换为 float 占用了相当多的执行时间。

我还为 math.pow 添加了一个基准测试,请注意,此函数与内置的 pow 不同,请参阅:Difference between the built-in pow() and math.pow() for floats, in Python?

关于python - 为什么 2**100 比 math.pow(2,100) 快这么多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28563187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com