python - 为什么这些常量函数的性能不同?
问题描述
在下面的代码片段中,为什么py_sqrt2
速度几乎是 的两倍np_sqrt2
?
from time import time
from numpy import sqrt as npsqrt
from math import sqrt as pysqrt
NP_SQRT2 = npsqrt(2.0)
PY_SQRT2 = pysqrt(2.0)
def np_sqrt2():
return NP_SQRT2
def py_sqrt2():
return PY_SQRT2
def main():
samples = 10000000
it = time()
E = sum(np_sqrt2() for _ in range(samples)) / samples
print("executed {} np_sqrt2's in {:.6f} seconds E={}".format(samples, time() - it, E))
it = time()
E = sum(py_sqrt2() for _ in range(samples)) / samples
print("executed {} py_sqrt2's in {:.6f} seconds E={}".format(samples, time() - it, E))
if __name__ == "__main__":
main()
$ python2.7 snippet.py
executed 10000000 np_sqrt2's in 1.380090 seconds E=1.41421356238
executed 10000000 py_sqrt2's in 0.855742 seconds E=1.41421356238
$ python3.6 snippet.py
executed 10000000 np_sqrt2's in 1.628093 seconds E=1.4142135623841212
executed 10000000 py_sqrt2's in 0.932918 seconds E=1.4142135623841212
请注意,它们是常量函数,仅从具有相同值的预计算全局变量中加载,并且常量仅在程序启动时的计算方式上有所不同。
此外,这些函数的反汇编表明它们按预期工作并且只访问全局常量。
In [73]: dis(py_sqrt2)
2 0 LOAD_GLOBAL 0 (PY_SQRT2)
2 RETURN_VALUE
In [74]: dis(np_sqrt2)
2 0 LOAD_GLOBAL 0 (NP_SQRT2)
2 RETURN_VALUE
解决方案
因为您每次都将它发送到 c 只为一个值
请尝试以下操作
t0=time.time()
numpy.sqrt([2]*10000)
t1 = time.time()
print("Took %0.3fs to do 10k sqrt(2)"%(t1-t0))
t0 = time.time()
for i in range(10000):
numpy.sqrt(2)
t1 = time.time()
print("Took %0.3fs to do 10k math.sqrt(2)"%(t1-t0))
推荐阅读
- mysql - MySQL-根据同一列的不同值计算总记录
- c++ - 我正在尝试构建 vst3 sdk 示例插件,但在 32 位 linux mint 19 上出现错误
- vuejs2 - Chatwoot,会话/Cookie 问题,即使在从 Vue 端注销后,在自定义添加的 Rails 视图上获取“current_user”
- docker - 如何将我们在其中的 ssh 容器转发到另一台服务器?
- prolog - 如何为 GNU-Prolog 程序创建可执行文件?
- vbscript - 任何尝试执行 vbs 脚本都会生成 File Not Found 错误
- php - Heroku url 禁止返回
- ios - 在单个画布上使用 CGContext 更改方形绘制的框架?
- visual-studio - 如何在 Visual Studio 调试器中漂亮地显示带有远程 gdb 的对象(可能通过适当的 natvis 文件)?
- r - 使用循环生成频率表并将其保存到 xlsx 文件