Python:帮助优化代码

时间:2014-07-11 15:59:02

标签: python optimization

我有一段代码用于计算矩形网格中的单元格中心。网格尺寸非常大(650列乘1150行)。代码运行速度很慢。我想知道是否可以使用任何技巧来减少运行时间。在下面的示例中,deltax是列间距的1D数组,deltay是行间距的1d数组。

center_x = np.empty((nrow,ncol),dtype ='double')
center_y = np.empty((nrow,ncol),dtype ='double')
for i in range(nrow-1,-1,-1):
    if(i == nrow-1):
        center_y[i,:] = 0.5*deltay[nrow-1]
    else:
        center_y[i,:] = center_y[i+1,:] + 0.5*deltay[i+1] + 0.5*deltay[i]

for j in range(0,ncol):
    if(j ==0):
        center_x[:,j] = 0.5*deltax[0]
    else:
        center_x[:,j]= center_x[0,j-1] + 0.5*deltax[j-1] + 0.5*deltax[j]

2 个答案:

答案 0 :(得分:1)

至少有两件事:

for i in range(nrow-1,-1,-1):
    if(i == nrow-1):
        center_y[i,:] = 0.5*deltay[nrow-1]
    else:
        center_y[i,:] = center_y[i+1,:] + 0.5*deltay[i+1] + 0.5*deltay[i]

可以更改以避免分支:

center_y[nrow-1,:] = 0.5*deltay[nrow-1]
for i in range(nrow-2,-1,-1):
    center_y[i,:] = center_y[i+1,:] + 0.5*deltay[i+1] + 0.5*deltay[i]

这会更多地利用numpy:

center_y[nrow-1,:] = 0.5*deltay[nrow-1]
center_y[:nrow-1, :] = 0.5*deltay[1:] + 0.5*deltay[:nrow-1]
# expl: deltay[i+1] in the loop skips the first element, deltay[i] skips the last element
for i in range(nrow-2,-1,-1): # can't move this part since center_y[i,:] depends on center_y[i+1,:] 
    center_y[i,:] = center_y[i+1,:] 

答案 1 :(得分:0)

center_x[:,j]= center_x[0,j-1] + 0.5*deltax[j-1] + 0.5*deltax[j]
...
center_y[i,:] = center_y[i+1,:] + 0.5*deltay[i+1] + 0.5*deltay[i]

您是否必须分配到[:,j][i,:]而不只是[i][j]?这类似于(但不完全是因为有多个维度)将其提升到O(n ^ 2)。