numpy vs Python map()中的矢量化

2024-09-29 00:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在比较计算大型阵列的方法,并想比较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个)


Tags: 方法函数numpynp方案temp速度平均值
1条回答
网友
1楼 · 发布于 2024-09-29 00:15:59

map如此之快是因为它实际上没有运行计算。它不会返回带有新值的新列表/数组,而是返回一个映射对象(迭代器),该对象仅在需要项时进行计算。你知道吗

为了进行公平的比较,您应该在第一部分的末尾执行list(celcius)。只有到那时,计算才得以执行。如果您的lambda(或另一个函数)的某个地方有一个print,您会看到map()本身并没有真正执行这些命令。你知道吗

阅读更多关于maphttps://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 list

相关问题 更多 >