我有一段我试图优化的python代码,但这样做实际上使速度降低了4倍。我不知道为什么。
def q_iteration(self, n:int):
"""Runs q_iteration on the state grid. raw_grid will not be affected"""
for i in range(n):
# Create structure to edit without affecting old data
new_grid = copy.deepcopy(self.state_grid)
for r in range(len(self.raw_grid)):
for c in range(len(self.raw_grid[r])):
new_grid[r][c].update_v(r, c, self.state_grid)
self.state_grid = new_grid
update_v
是一项繁重的操作,程序速度变得非常成问题。我决定除了优化update_v
之外,还更改了引用,以免每次迭代都不会创建新的深层副本。
def q_iteration(self, n:int):
"""Runs q_iteration on the state grid. raw_grid will not be affected. Resets any previous iteration"""
# create copy to edit
nxt = copy.deepcopy(self.state_grid)
# create copy to reference data
curr = self.state_grid
# clear the current data
for r in range(len(nxt)):
for c in range(len(curr)):
curr[r][c].v = 0
# update v values
for i in range(n):
for r in range(len(self.raw_grid)):
for c in range(len(self.raw_grid[r])):
nxt[r][c].update_v(r, c, curr)
# swap references to overwrite current next iteration
curr, nxt = nxt, curr
# set the reference back into the data
self.state_grid = curr
对我来说没有什么意义的是为什么不创建深层副本实际上要慢?有人可以解释吗?
编辑:这是update_v