我需要此功能进行优化,因为我试图让我的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