我在比较大数组的计算方法,并希望比较numpy中广播运营商的速度和替代方案的速度。不过,看到python map()函数的速度之快,我感到很惊讶,我想知道是否有人能解释一下为什么这比广播快得多。
广播
%%timeit farenheit = np.linspace( -10, 20, 1000 )
celcius = (farenheit - 32) * (5/9)4.5s±99.4ns/环(平均±std )。dev.7次运行中,每一次循环100000次)
列表理解
%%timeit farenheit = np.linspace( -10, 20, 1000 )
[(temp - 32) * (5/9) for temp in farenheit]886±4.56s/环(平均±std )。dev.7次运行中,每一次有1000次循环)
map() Python 3
%%timeit farenheit = np.linspace( -10, 20, 1000 )
celcius = map(lambda temp: (temp - 32) * (5/9), farenheit)每环248 ns±41.9 ns (平均±std )。dev.7次运行中,每一次循环1000000次)
发布于 2019-09-14 17:06:02
map速度如此之快,因为它实际上没有运行计算。它不返回带有新值的新列表/数组,而是返回一个map对象(迭代器),该对象仅在需要项时才进行计算。
为了进行公平的比较,您应该在第一部分的末尾执行list(celcius)。只有到那时才能执行计算。如果您的lambda (或其他函数)在其中某个地方有一个print,那么您将看到map()本身还没有真正执行这些命令。
阅读有关map:https://docs.python.org/3/library/functions.html#map的更多信息
举个例子:
def double(x):
print('hi')
return x*2
a = [1,2,3]
b = map(double, a)
# notice nothing is printing, the calculation isn't happening as well
c = list(b) # this will print 'hi' 3 times as well as returning the doubled listhttps://stackoverflow.com/questions/57937570
复制相似问题