1
我想知道是否有人能夠幫助我理解爲什麼以下兩個程序以明顯不同的速度運行(第一個以1/10秒爲單位,第二個以3秒爲單位)。瞭解numpy數組的運行時間嗎?
def gaussian(x, h, m, c):
return list(h * exp(-(x-m)**2/(2*c**2)))
x = np.linspace(0, 1000, 1001)
for i in range(1000):
gaussian(x, 50, 500, 10)
和
def gaussian2(x, h, m, c):
def computer(x):
return h * exp(-(x-m)**2/(2*c**2))
y = []
for val in x:
y.append(computer(val))
return y
x = np.linspace(0, 1000, 1001)
for i in range(1000):
gaussian2(x, 50, 500, 10)
我需要第二個版本的唯一原因是因爲它讓我看看列表中的所有元素,所以我可以用它們來進行其它操作(在未示出這個例子)。但這不是我所要求的 - 我在問爲什麼第二種形式比第一種慢得多。
謝謝!
因爲(假設'exp'函數是從numpy導入的)第一個函數與向量化數據(向量/數組/列/等)一起工作,第二個函數與標量值一起工作。 numpy中的大多數向量化操作都是使用Cython實現的,與其標量替代方法相比,__much__更快... – MaxU
是'exp''np.exp'還是'math.exp'? – hpaulj