我一直在為我正在構建的一個程式優化一些歐氏距離轉換的計算。首先,除了參加一些MOOC課程外,我在計算機科學方面幾乎沒有接受過正式培訓。
我通過在 Python 中的經驗測驗了解到,為單個變數賦值并對其進行操作要比對陣列進行操作快。這個觀察結果對其他人來說是可重復的嗎?
如果是這樣,誰能更深入地解釋一下為什么這兩種形式的語法之間存在如此大的速度差異?
請看下面的一些示例代碼。
import numpy as np
from math import sqrt
import time
# Numpy陣列數學
def test1(coords)。
結果 = []
for coord in coords:
mins = np.array([1,1,1] )
# 下面的三行似乎比np.linalg.norm()更快。
mins = (coord - mins)**2
mins = np.sum(Mins)
results.append(sqrt(mins))
# 單獨的變數分配數學
def test2(coords)。
結果 = []
for point in coords:
z, y, x = 1, 1, 1。
z = (point[0] - z)**2)
y = (point[1] - y)**2)
x = (point[2] - x)**2)
mins = sqrt(z y x)
results.append(mins)
a = np.random.randint(0, 10, (500000,3)
t = time.perf_counter()
test1(a)
print ("Test 1 speed:"/span>, time.perf_counter() - t)
t = time.perf_counter()
test2(a)
print ("Test 2 speed:"/span>, time.perf_counter() - t)
- 測驗1的速度:3.261552719秒 測驗2的速度:0.716983475 s。
uj5u.com熱心網友回復:
Python的操作和記憶體分配通常比Numpy的高度優化的矢量陣列操作慢得多。因為你在陣列上回圈操作并分配記憶體,所以你無法獲得Numpy提供的任何好處。這在你的第一個代碼中尤其糟糕,因為它導致了對小陣列的不適當的分配。
將你的代碼與將所有操作卸載到 Numpy 而不是讓 Python 一個一個地進行操作的代碼相比較:
def test3(coords)。
mins = (coords - 1)**2。
結果 = np.sqrt(np.sum(Mins, axis=1)
return result
在我的系統中,這個結果是:
測驗1速度。4.995761550962925
測驗2速度。1.3881473205983639
測驗3速度。0.05562112480401993
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/322407.html
標籤:
