python - 为什么这更慢?
问题描述
我有一段我试图优化的 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
解决方案
推荐阅读
- wordpress - 给图片和视频添加关键词——Wordpress
- c++ - 如何修复地形纹理?
- r - 当几何图形不同时在ggplot中合并图例
- reactjs - 开玩笑使用 ES6 导入/导出 SyntaxError: Unexpected token'export' 出现错误
- azure - 在已建立隧道的混合 Azure 环境中,是否可以使用单独的用户 vpn 访问本地地址?
- javascript - 循环后执行的循环中的 Promise 回调
- python - 在 PyQt5 中按下“ctrl”时如何防止滚动?
- excel - 如何将数据字典“X”中的数据(300 到 500 个数据集)导出到 Excel 并命名列标题
- spring - 在带有 thymleaf 的 Spring MVC 中显示一个列表
- php - 如何使用 php pdo 搜索多个输入和复选框?