我需要此功能進行優化,因爲我試圖讓我的OpenGL模擬運行速度更快。我想使用Parakeet,但我無法完全理解我需要如何修改下面的代碼才能這樣做。你能看到我應該做什麼嗎?使用Parakeet優化Python函數
def distanceMatrix(self,x,y,z):
" ""Computes distances between all particles and places the result in a matrix such that the ij th matrix entry corresponds to the distance between particle i and j"" "
xtemp = tile(x,(self.N,1))
dx = xtemp - xtemp.T
ytemp = tile(y,(self.N,1))
dy = ytemp - ytemp.T
ztemp = tile(z,(self.N,1))
dz = ztemp - ztemp.T
# Particles 'feel' each other across the periodic boundaries
if self.periodicX:
dx[dx>self.L/2]=dx[dx > self.L/2]-self.L
dx[dx<-self.L/2]=dx[dx < -self.L/2]+self.L
if self.periodicY:
dy[dy>self.L/2]=dy[dy>self.L/2]-self.L
dy[dy<-self.L/2]=dy[dy<-self.L/2]+self.L
if self.periodicZ:
dz[dz>self.L/2]=dz[dz>self.L/2]-self.L
dz[dz<-self.L/2]=dz[dz<-self.L/2]+self.L
# Total Distances
d = sqrt(dx**2+dy**2+dz**2)
# Mark zero entries with negative 1 to avoid divergences
d[d==0] = -1
return d, dx, dy, dz
從我可以告訴,鸚鵡應該能夠使用上面的功能沒有改變 - 它僅使用NumPy的和數學。但是,我總是從鸚鵡JIT包裝調用函數時出現以下錯誤:
AssertionError: Unsupported function: <bound method Particles.distanceMatrix of <particles.Particles instance at 0x04CD8E90>>
你也可以做的一種可能的優化方法是用一個局部變量替換'self.L/2'的12個用法。這可能會做點什麼。 :-)(雖然這對鸚鵡問題沒有幫助......抱歉) –
我猜布爾索引不支持,但我不確定。我知道分配像xtemp和dx L/2這樣的中間數組是浪費的。儘管你的向量化代碼可能是常規numpy中的快速代碼,但使用JIT編譯器,最好使用鈍的for-loops! – 2013-11-24 14:49:55