Holy CPU cycles batman!
的確如此。
但請注意考慮一些與numpy
非常基本相關的內容;基於複雜線性代數的功能(如random numbers
或singular value decomposition
)。現在,考慮這些seamingly簡單算了一筆賬:
In []: A= rand(2560000, 3)
In []: %timeit rand(2560000, 3)
1 loops, best of 3: 296 ms per loop
In []: %timeit u, s, v= svd(A, full_matrices= False)
1 loops, best of 3: 571 ms per loop
,並請相信我,這樣的表現也不會顯著當前可用的任何包毆打。
所以,請描述您的真實問題,我會盡力找出適合它的體面的numpy
解決方案。
更新:
下面是一些簡單的雷球路口代碼:
import numpy as np
def mag(X):
# magnitude
return (X** 2).sum(0)** .5
def closest(R, c):
# closest point on ray to center and its distance
P= np.dot(c.T, R)* R
return P, mag(P- c)
def intersect(R, P, h, r):
# intersection of rays and sphere
return P- (h* (2* r- h))** .5* R
# set up
c, r= np.array([10, 10, 10])[:, None], 2. # center, radius
n= 5e5
R= np.random.rand(3, n) # some random rays in first octant
R= R/ mag(R) # normalized to unit length
# find rays which will intersect sphere
P, b= closest(R, c)
wi= b<= r
# and for those which will, find the intersection
X= intersect(R[:, wi], P[:, wi], r- b[wi], r)
顯然,我們正確地計算出:
In []: allclose(mag(X- c), r)
Out[]: True
和一些計時:
In []: % timeit P, b= closest(R, c)
10 loops, best of 3: 93.4 ms per loop
In []: n/ 0.0934
Out[]: 5353319 #=> more than 5 million detection's of possible intersections/ s
In []: %timeit X= intersect(R[:, wi], P[:, wi], r- b[wi])
10 loops, best of 3: 32.7 ms per loop
In []: X.shape[1]/ 0.0327
Out[]: 874037 #=> almost 1 million actual intersections/ s
這些時間是用非常適中的機器完成的。使用現代化的機器,仍然可以期待顯着的加速。
無論如何,這只是一個簡短的演示如何使用numpy
進行編碼。
一個簡單的想法:'numpy.array'實際上是一個比列表更復雜的數據結構。在第二個代碼片段中,您創建了一個列表**和**一個numpy數組(僅在第一個列表中)。這是否是造成如此巨大差異的唯一原因,我不能說。 –
@Felix:好的,但創建列表的速度很快,所以即使我在第二種情況下創建了一個列表和一個numpy數組,它仍然是這裏的熱點,並且無論結構有多複雜是的,它仍然是該死的昂貴... –
但是考慮:創建數據很少是應用程序的瓶頸,它使用numpy如此複雜。我不知道幕後會發生什麼,但顯然會在一天結束時讓數學較重的程序更快,所以沒有理由抱怨;) – delnan