Python的地图和过滤器真的快得离谱,还是我的测量是错误的?



我对向量/列表上的操作进行一些速度测试。令人惊讶的是,mapfilter似乎以5-10倍的倍数击败numpy。请参阅以下给定时间的以下简短代码示例(下面的完整代码。):

n = 10000000
a = np.random.rand(n)
b = np.random.rand(n)
c = a + b # time = 0.07 s
d = a[a < 0.3] # time = 0.09 s
a = [random.random() for x in range(0, n, 1)]
b = [random.random() for x in range(0, n, 1)]
c = map(lambda x, y: x + y, a, b) # time = 0.006s
d = filter(lambda e: e < 0.3, a) # time = 0.001s

mapfilter真的比numpy操作快得多吗?还是我的测量有缺陷?您可以看到下面的完整代码:

import numpy as np
import time
import random
class StopWatch:
    def __init__(self, str):
        self.str = str
        self.t = time.time()
    def stop(self):
        t = time.time()
        print("time = " + str(t - self.t) + " s for " + self.str)
n = 10000000
a = np.random.rand(n)
b = np.random.rand(n)
sw = StopWatch('numpy')
c = a + b
sw.stop()
sw = StopWatch('numpy')
d = a[a < 0.3]
sw.stop()
a = [random.random() for x in range(0, n, 1)]
b = [random.random() for x in range(0, n, 1)]
sw = StopWatch('list')
c = map(lambda x, y: x + y, a, b)
sw.stop()
sw = StopWatch('list')
d = filter(lambda e: e < 0.3, a)
sw.stop()

如果我的测量正确,为什么要快得多?

我的猜测是实际上没有计算c = map(lambda x, y: x + y, a, b)。在Python 3中,对mapfilter进行了懒惰,因此在必须评估它们之前就没有。

您可以通过在停止计时器之前添加list(c)来验证这一点,尽管这可能会影响列表创建的时间。

最新更新