我正在比较计算大型阵列的方法,并想比较numpy和其他方案中广播运营商的速度。我惊讶地看到pythonmap()
函数的速度,我想知道是否有人能解释为什么它比广播快得多。你知道吗
广播
%%timeit farenheit = np.linspace( -10, 20, 1000 )
celcius = (farenheit - 32) * (5/9)
每个回路4.5µs±99.4 ns(7次运行的平均值±标准偏差,每个100000个回路)
列表理解
%%timeit farenheit = np.linspace( -10, 20, 1000 )
[(temp - 32) * (5/9) for temp in farenheit]
每个回路886µs±4.56µs(7次运行的平均值±标准偏差,每个回路1000个)
Python 3map()
%%timeit farenheit = np.linspace( -10, 20, 1000 )
celcius = map(lambda temp: (temp - 32) * (5/9), farenheit)
每个回路248纳秒±41.9纳秒(7次运行的平均值±标准偏差,每个回路1000000个)
map
如此之快是因为它实际上没有运行计算。它不会返回带有新值的新列表/数组,而是返回一个映射对象(迭代器),该对象仅在需要项时进行计算。你知道吗为了进行公平的比较,您应该在第一部分的末尾执行
list(celcius)
。只有到那时,计算才得以执行。如果您的lambda
(或另一个函数)的某个地方有一个print
,您会看到map()
本身并没有真正执行这些命令。你知道吗阅读更多关于
map
:https://docs.python.org/3/library/functions.html#map举个例子:
相关问题 更多 >
编程相关推荐