我從來沒有關心過這個問題,但現在我需要使用一些需要被PyOpenGL緩衝的大量頂點,而且好像python迭代是瓶頸。這是情況。我有一個3D點陣列vertices
,並且在每一步我都必須爲每個頂點計算一個4D的顏色數組。我的做法迄今:在python中迭代的最快方法
upper_border = len(self.vertices)/3
#Only generate at first step, otherwise use old one and replace values
if self.color_array is None:
self.color_array = numpy.empty(4 * upper_border)
for i in range(upper_border):
#Obtain a color between a start->end color
diff_activity = (activity[i] - self.min)/abs_diff
clr_idx = i * 4
self.color_array[clr_idx] = start_colors[0] + diff_activity * end_colors[0]
self.color_array[clr_idx + 1] = start_colors[1] + diff_activity * end_colors[1]
self.color_array[clr_idx + 2] = start_colors[2] + diff_activity * end_colors[2]
self.color_array[clr_idx + 3] = 1
現在我不認爲有什麼我可以做,以消除來自循環的每一步操作,但我猜,必須有一個更優化的性能的方法做那個循環。我在說,因爲在JavaScript中,例如,同樣的微積分產生9FPS,而在Python中,我只得到2-3 FPS。
問候, 波格丹
如果您使用python 2,請用'xrange'替換'range'。 –
如果迭代確實是瓶頸,那麼有一種可能性是在Cython中重新編碼循環:http://cython.org/ – NPE