1 回答

TA贡献1873条经验 获得超9个赞
使用您的函数和以下代码来分析速度
import time
shape = (10, 1440)
matrix = np.zeros(shape)
sim_start = 0
sim_end = 1440
searches = generate_searches(1000000, sim_start, sim_end)
def reset():
matrix[:] = 0
def test_matrix_speed():
for i in searches:
search_start = i[0]
search_end = i[1]
availability = search_and_book_availability(matrix, search_start, search_end)
def timeit(func):
# warmup
reset()
func()
reset()
start = time.time()
func()
end = time.time()
return end - start
print(timeit(test_matrix_speed))
我发现jited 版本大约为 11.5s,而没有jit. 我不是 numba 方面的专家,但它的目的是优化以非矢量化方式编写的数字代码,尤其是显式for循环。在您的代码中没有,您只使用矢量化操作。因此,我预计jit不会超过基线解决方案,但我必须承认,我很惊讶地看到它更糟。如果您想优化您的解决方案,您可以使用以下代码减少执行时间(至少在我的 PC 上):
def search_and_book_availability_opt(matrix, search_start, search_end):
search_slice = matrix[:, search_start:search_end]
# we don't need to sum in order to check if all elements are 0.
# ndarray.any() can use short-circuiting and is therefore faster.
# Also, we don't need the selected values from np.where, only the
# indexes, so np.nonzero is faster
bookable, = np.nonzero(~search_slice.any(axis=1))
# short circuit
if bookable.size == 0:
return False
# we can perform random choice even if size is 1
id_to_book = np.random.choice(bookable)
matrix[id_to_book, search_start:search_end] = 1
return True
并通过初始化matrix为np.zeros(shape, dtype=np.bool),而不是默认值float64。我能够获得大约 3.8 秒的执行时间,比您的 unjited 解决方案提高了约 50%,比 jted 版本提高了约 70%。希望有帮助。
添加回答
举报