Skip to main content
 首页 » 编程设计

python之numpy 与 Python map() 中的矢量化

2024年11月01日36JustinYoung

我正在比较针对大型数组进行计算的方法,并想比较 numpy 中广播运算符与替代方案的速度。不过,我很惊讶地看到 python map() 函数的速度,并且想知道是否有人可以解释这为什么比广播快得多。

广播

%%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 3 map()

%%timeit farenheit = np.linspace( -10, 20, 1000 ) 
celcius = map(lambda temp: (temp - 32) * (5/9), farenheit) 

每个循环 248 ns ± 41.9 ns(7 次运行的平均值 ± 标准差,每次 1000000 次循环)

请您参考如下方法:

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 list