问题:
在对我编写的数据分析代码进行行分析之后,我发现大约70%的运行时间集中在对两个不同数组操作例程的调用上。我最终希望以实时方式分析数据,所以这里的任何优化都会有很大帮助。
这两个函数获取左边的矩阵并将其转换为右边的形式(反之亦然)。
我感兴趣的矩阵目前存储为N乘n2d numpy数组(其中N是偶数)。
代码:
为此,我编写了以下代码:
# Shifts elements of a vector to the left by the given amount.
def Vec_shift_L(vec, shift=0):
s = vec.size
out = np.zeros(s, dtype=complex)
out[:s-shift] = vec[shift:]
out[s-shift:] = vec[:shift]
return out
# Shifts elements of a vector to the right by the given amount.
def Vec_shift_R(vec,shift=0):
s=vec.size
out=np.zeros(s, dtype=complex)
out[:shift] = vec[s-shift:]
out[shift:] = vec[:s-shift]
return out
# Shifts a matrix from the left form (above) to the right form.
def OP_Shift(Trace):
s = Trace.shape
Out = np.zeros(s, dtype=complex)
for i in np.arange(s[0]):
Out[i,:] = Vec_shift_L(Trace[i,:], (i+s[0]/2) % s[0])
for i in np.arange(s[0]):
Out[i,:] = np.flipud(Out[i,:])
return Out
# Shifts a matrix from the right form (above) to the left form.
def iOP_Shift(Trace):
s = Trace.shape
Out = np.zeros(s, dtype=complex)
for i in np.arange(s[0]):
Out[i,:] = np.flipud(Trace[i,:])
for i in np.arange(s[0]):
Out[i,:] = Vec_shift_R(Out[i,:], (i+s[0]/2) % s[0])
return Out
在最初编写本文时,我并没有意识到numpy的roll函数,所以我编写了vec_shift函数来代替它。在我目前的系统上,他们似乎比使用roll的性能提高了30%左右。
有没有办法进一步提高这段代码的性能?
让^{} 帮你解决一个矢量化的解决方案!在
相关问题 更多 >
编程相关推荐