python字符串数组切片性能_python – 为数组切片赋值很慢
我正在嘗試通過在Cython中實現(xiàn)它來優(yōu)化
Python算法.我的問題是關于以下代碼中存在的某個性能瓶頸:
@cython.boundscheck(False) # turn off bounds-checking for entire function
def anglesToRGB( np.ndarray[double, ndim=2] y, np.ndarray[double, ndim=2] x ):
cdef double angle
cdef double Hp
cdef double C
cdef double X
cdef np.ndarray[double, ndim=3] res = np.zeros([y.shape[0], y.shape[1], 3], dtype=np.float64)
for i in xrange(y.shape[0]):
for j in xrange(y.shape[1]):
angle = atan2( y[i,j], x[i,j] )*180.0/PI+180
C = sqrt(pow(y[i,j],2)+pow(x[i,j],2))/360.0 #Chroma
Hp = angle/60.0
X = C*(1-fabs( Hp%2-1))
C *= 255
X *= 255
if (0. <= Hp < 1.):
res[i,j,:] = [C,X,0]
elif (1. <= Hp < 2.):
res[i,j,:] = [X,C,0]
elif (2. <= Hp < 3.):
res[i,j,:] = [0,C,X]
elif (3. <= Hp < 4.):
res[i,j,:] = [0,X,C]
elif (4. <= Hp < 5.):
res[i,j,:] = [X,C,C]
else:
res[i,j,:] = [C,0,X]
return res
我已經確定了當我為res數組的一個片段分配值列表時的主要瓶頸,
喜歡
res[i,j,:] = [C,X,0]
但是,如果我將作業(yè)更改為
res[i,j,0] = C
res[i,j,1] = X
res[i,j,2] = 0
然后代碼運行速度提高了幾個數量級.
對我來說這很奇怪,因為Cython編譯器肯定應該足夠聰明地為我做這個嗎?或者我是否需要首先提供一些提示?
我應該注意到,將切片更改為0:3而不是:并且將值列表設置為numpy數組不會提高性能.
我想知道的是為什么這個操作如此糟糕地殺死性能,如果有任何方法可以解決它而不必犧牲方便的列表和切片表示法.
最好的祝福
總結
以上是生活随笔為你收集整理的python字符串数组切片性能_python – 为数组切片赋值很慢的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hive 如何将数组转成字符串_hive
- 下一篇: 9. 设计二个函数分别计算sinx和co