两个n维向量的点积u=[u1,u2,...un]和v=[v1,v2,...,vn]被由下式给出u1*v1 + u2*v2 + ... + un*vn.
昨天发布的一个问题鼓励我找到使用标准库,没有第三方模块或C/Fortran/C++调用来在Python中计算点积的最快方法.
我计时了四种不同的方法; 到目前为止,最快的似乎是sum(starmap(mul,izip(v1,v2)))(来自模块的地方starmap和izip来自itertools).
对于下面给出的代码,这些是经过的时间(以秒为单位,一百万次运行):
d0: 12.01215
d1: 11.76151
d2: 12.54092
d3: 09.58523
Run Code Online (Sandbox Code Playgroud)
你能想到更快的方法吗?
import timeit # module with timing subroutines
import random # module to generate random numnbers
from itertools import imap,starmap,izip
from operator import mul
def v(N=50,min=-10,max=10):
"""Generates a random vector (in an array) of dimension N; the
values are integers in the range [min,max]."""
out = …Run Code Online (Sandbox Code Playgroud) 是否有任何我想使用的内存、速度或其他原因:
tuple(i for i in range(5000))
Run Code Online (Sandbox Code Playgroud)
代替:
[i for i in range(5000)]
Run Code Online (Sandbox Code Playgroud)
如果我不介意元组的不变性