如何使循环更快?你知道吗
import numpy as np
# naively small input data
image = np.array( [[2,2],[2,2]] )
polarImage = np.array( [[0,0],[0,0]] )
a = np.array( [[0,0],[0,1]] )
r = np.array( [[0,0],[0,1]] )
# TODO - this loop is too slow
it = np.nditer(image, flags=['multi_index'])
while not it.finished:
polarImage[ a[it.multi_index],r[it.multi_index] ] += it[0]
it.iternext()
print polarImage
# this is fast but doesn't cumulate the results!
polarImage = np.array( [[0,0],[0,0]] )
polarImage[a,r]+= image
print polarImage
第一次打印返回:
[[6 0]
[0 2]]
第二条:
[[2 0]
[0 2]]
通过累积加法,我的意思是有时两个或多个来自图像的值必须加到极化的一个单元格中
在这种情况下,
nditer
的使用模糊了过程,而没有提高速度。我们更习惯于看到双循环:polarImage[a,r]+= image
由于缓冲问题而无法工作。(0,0)
索引对使用了3次。有一种ufunc
方法专门用于这种情况,at
。它执行无缓冲操作;很可能使用与第一个示例相同的nditer
,但在编译代码中。你知道吗相关问题 更多 >
编程相关推荐