蟒蛇;实现逐元素向量乘法的最高效方法

时间:2012-01-11 22:30:05

标签: python performance

我需要function-aggregator,它会将两个列表减少到一个总数。 '项目'应该是布尔人的矢量。

所以,我写了这些函数:

def element_wise_multiplication(weights, items):
    return map(lambda x, y: x * y, weights, items)

def total(weights, items):
    return sum(element_wise_multiplication(weights, items))

他们看起来对我很好,但问题是分析器显示其中带有lambda的行占95%的运行时间,因此它的性能几乎是不可接受的。

实施它的最有效方法是什么?

P.S。我知道NumPy的数组,但我想在这个上使用PyPy。或者在这种情况下使用它不值得吗?

3 个答案:

答案 0 :(得分:3)

您可以使用如下的生成器来处理:

from itertools import izip
value = sum((x * y) for x, y in izip(weights, items))

izip完成与内置zip相同的操作,但没有内存开销。

答案 1 :(得分:2)

虽然你提到不希望在这种情况下使用numpy,但可能值得一看速度差异。

最好的非numpy解决方案似乎是使用izip的生成器,它略微优于zip。

    In [31]: %timeit sum(x*y for x,y in zip(weights,items))
    10000 loops, best of 3: 158 us per loop

    In [32]: %timeit sum(x*y for x,y in izip(weights,items))
    10000 loops, best of 3: 125 us per loop

然而,当我们使用numpy数组时,我们得到:

    In [33]: %timeit (np_weights,np_items).sum()
    100000 loops, best of 3: 9.08 us per loop

numpy解决方案的速度提高了整整14倍。如果这确实是你代码中的瓶颈,那么numpy就是你要走的路。

答案 2 :(得分:1)

试试这个:

def total(weights, items):
   return sum (x * y for x, y in zip(weights, items))  
相关问题