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

Kri*_*arG 2 python numpy

这是使用 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)
Run Code Online (Sandbox Code Playgroud)

挂壁时间:11 毫秒

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)
Run Code Online (Sandbox Code Playgroud)

挂壁时间:4.78 秒

4998161.0032265792

Pau*_*zer 5

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

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