gpt4 book ai didi

python - 为什么 np.dot 比使用 for 循环求点积快得多

转载 作者:行者123 更新时间:2023-11-30 22:42:13 25 4
gpt4 key购买 nike

这是使用 np.dot 的时间:

import numpy as np
import timeit

x = np.random.random(size=10**7)
a = np.ones(x.size)

%time np.dot(x, a)

Wall time: 11 ms

5001679.267011214

这是使用 for 循环的时间:

import numpy as np
import timeit

x = np.random.random(size=10**7)
a = np.ones(x.size)

def innfeldi(vigur1, vigur2):
return sum([vigu1[i]*vigur2[i] for i in range(len(vigur1))])

%timeit innfeldi(x, a)

Wall time: 4.78 s

4998161.0032265792

最佳答案

因为np.dot在编译代码中执行实际的算术运算和封闭循环,这比Python解释器快得多。

这个原则,将重复的东西组合在一起并尽可能地去掉解释器,这就是为什么我们可以用Python或Matlab等高级语言编写以可接受的速度运行的数字代码。

关于python - 为什么 np.dot 比使用 for 循环求点积快得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42227432/

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