【发布时间】:2010-10-22 20:23:51
【问题描述】:
我正在 Python 中运行一个模型,并试图加快执行时间。通过分析代码,我发现大量的总处理时间花费在下面的cell_in_shadow 函数中。我想知道有没有什么办法可以加快速度?
该函数的目的是提供一个布尔响应,说明 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? -
我不确定如何分辨哪些线条比其他线条重。你知道怎么做吗?我已经检查了我对它的所有调用,我只在需要时调用它。
-
@robintw:您是否为
x和y的每个可能值调用cell_in_shadow? -
是的,但是
grid数组在每次调用之间都会发生变化,所以我不能使用映射函数:( -
@robintw 好吧,问题的很大一部分。如果有 M 行(x 坐标)和 N 列(y 坐标),那么您的算法本质上是 O(M^2*N)。
标签: python performance numpy