我正在Python中的模型,我試圖加快執行時間。通過分析代碼,我發現在下面的函數中花費了大量的總處理時間。我想知道是否有任何方法來加速它?加快NumPy的循環
功能的目的是提供一種布爾響應,指出是否NumPy的陣列的指定小區由另一小區的陰影(只在x方向上)。它通過逐步向後逐步檢查每個單元格的高度,以使得給定單元格處於陰影中來實現此目的。在shadow_map
值由這裏未示出的另一個函數來計算 - 對於這個例子,取shadow_map
爲與類似值的數組:
[0] = 0 (not used)
[1] = 3
[2] = 7
[3] = 18
的add_x
功能用來確保數組的下標環周圍(使用時鐘面算術),因爲網格具有周期性邊界(任何一邊離開一邊都會重新出現在另一邊)。
def cell_in_shadow(x, y):
"""Returns True if the specified cell is in shadow, False if not."""
# Get the global variables we need
global grid
global shadow_map
global x_len
# Record the original length and move to the left
orig_x = x
x = add_x(x, -1)
while x != orig_x:
# Gets the height that's needed from the shadow_map (the array index is the distance using clock-face arithmetic)
height_needed = shadow_map[((x - orig_x) % x_len)]
if grid[y, x] - grid[y, orig_x] >= height_needed:
return True
# Go to the cell to the left
x = add_x(x, -1)
def add_x(a, b):
"""Adds the two numbers using clockface arithmetic with the x_len"""
global x_len
return (a + b) % x_len
'cell_in_shadow'中是否有比其他人更重的特殊行?你是否儘可能少地調用'cell_in_shadow'? – nmichaels 2010-10-22 20:29:23
我不知道如何判斷哪條線比其他線更重。你知道如何做到這一點?我已經檢查了我的所有電話,只有在需要時纔會打電話給它。 – robintw 2010-10-22 20:31:23
@robintw:你是否爲'x'和'y'的每個可能的值調用'cell_in_shadow'? – unutbu 2010-10-22 21:47:00