两个n维向量 u=[u1,u2,...un]
和 v=[v1,v2,...,vn]
的点积是 u1*v1 + u2*v2 + ... + un*vn
。
昨天有一个问题让我寻找使用Python标准库计算点积的最快方法而不借助于第三方模块或C/Fortran/C++的调用。
我测试了四种不同的方法;目前最快的似乎是sum(starmap(mul,izip(v1,v2)))
(其中starmap
和izip
来自于itertools
模块)。
对于下面所呈现的代码,这些是经过的时间(以秒为单位,对于一百万次运行):
d0: 12.01215
d1: 11.76151
d2: 12.54092
d3: 09.58523
你能想到更快的处理方法吗?
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 = []
for k in range(N):
out.append(random.randint(min,max))
return out
def check(v1,v2):
if len(v1)!=len(v2):
raise ValueError,"the lenght of both arrays must be the same"
pass
def d0(v1,v2):
"""
d0 is Nominal approach:
multiply/add in a loop
"""
check(v1,v2)
out = 0
for k in range(len(v1)):
out += v1[k] * v2[k]
return out
def d1(v1,v2):
"""
d1 uses an imap (from itertools)
"""
check(v1,v2)
return sum(imap(mul,v1,v2))
def d2(v1,v2):
"""
d2 uses a conventional map
"""
check(v1,v2)
return sum(map(mul,v1,v2))
def d3(v1,v2):
"""
d3 uses a starmap (itertools) to apply the mul operator on an izipped (v1,v2)
"""
check(v1,v2)
return sum(starmap(mul,izip(v1,v2)))
# generate the test vectors
v1 = v()
v2 = v()
if __name__ == '__main__':
# Generate two test vectors of dimension N
t0 = timeit.Timer("d0(v1,v2)","from dot_product import d0,v1,v2")
t1 = timeit.Timer("d1(v1,v2)","from dot_product import d1,v1,v2")
t2 = timeit.Timer("d2(v1,v2)","from dot_product import d2,v1,v2")
t3 = timeit.Timer("d3(v1,v2)","from dot_product import d3,v1,v2")
print "d0 elapsed: ", t0.timeit()
print "d1 elapsed: ", t1.timeit()
print "d2 elapsed: ", t2.timeit()
print "d3 elapsed: ", t3.timeit()
注意文件名必须为dot_product.py
才能运行脚本;我在Mac OS X Version 10.5.8上使用Python 2.5.1。编辑:
我对N=1000运行了这个脚本,并得到了以下结果(以秒为单位,运行一百万次):
d0: 205.35457
d1: 208.13006
d2: 230.07463
d3: 155.29670
我想可以肯定地说,事实上,选项三是最快的选项,选项二是最慢的选项(四个选项中所提供的)。