首页 > 解决方案 > 为什么这更慢?

问题描述

我有一段我试图优化的 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

https://pastebin.com/cS2T8Z5t

标签: pythonperformance

解决方案


推荐阅读