首页 > 解决方案 > 有没有办法优化我的列表理解以获得更好的性能?它比 for 循环慢

问题描述

我正在尝试优化我的代码以循环通过 ASC 光栅文件。该函数的输入是来自 ASC 文件的数据数组,形状为 1.000 x 1.000(1mio 数据点)、ASC 文件信息和列跳过值。在这种情况下,跳过值并不重要。

如果数据 == nodata_value,我的带有 for 循环代码的函数执行得不错并跳过了一个数组单元格。这是功能:

def asc_process_single(self, asc_array, asc_info, skip=1):
    # ncols = asc_info['ncols']
    nrows = asc_info['nrows']
    xllcornor = asc_info['xllcornor']
    yllcornor = asc_info['yllcornor']
    cellsize = asc_info['cellsize']
    nodata_value = asc_info['nodata_value']

    raster_size_y = cellsize*nrows
    # raster_size_x = cellsize*ncols

    # Looping over array rows and cols with skipping
    xyz = []
    for row in range(asc_array.shape[0])[::skip]:
        for col in range(asc_array.shape[1])[::skip]:
            val_z = asc_array[row, col]  # Z value of datapoint

            # The no data value is not processed
            if val_z == nodata_value:
                pass
            else:
                # Xcoordinate for current Z value
                val_x = xllcornor + (col * cellsize)

                # Ycoordinate for current Z value
                val_y = yllcornor + raster_size_y - (row * cellsize)

                # x, y, z to LIST
                xyz.append([val_x, val_y, val_z])
    return xyz

在存在 nodata_value(s) 的 ASC 文件上重复 7 次的时间是:

593 ms ± 34.4 ms per loop (mean ± std. dev. of 10 runs, 1 loop each)

我认为我可以通过列表理解做得更好:

def asc_process_single_listcomprehension(self, asc_array, asc_info, skip=1):
        # ncols = asc_info['ncols']
        nrows = asc_info['nrows']
        xllcornor = asc_info['xllcornor']
        yllcornor = asc_info['yllcornor']
        cellsize = asc_info['cellsize']
        nodata_value = asc_info['nodata_value']

        raster_size_y = cellsize*nrows
        # raster_size_x = cellsize*ncols

        # Looping over array rows and cols with skipping
        rows = range(asc_array.shape[0])[::skip]
        cols = range(asc_array.shape[1])[::skip]
        
        xyz = [[xllcornor + (col * cellsize),
               yllcornor + raster_size_y - (row * cellsize),
               asc_array[row, col]]
               for row in rows for col in cols
               if asc_array[row, col] != nodata_value] 
        
        return xyz

但是,这比我的 for 循环执行得慢,我想知道为什么?

757 ms ± 58.4 ms per loop (mean ± std. dev. of 10 runs, 1 loop each)

是因为列表推导式查找 asc_array[row, col] 两次吗?仅此操作一项成本

193 ns ± 11.4 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

而不是仅使用我的 for 循环中数组中已查找值的 z 值进行分配

51.2 ns ± 1.18 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

执行此操作 1 mio 次将增加执行此操作以进行列表理解的时间。任何想法如何进一步优化我的列表理解,使其比我的 for 循环性能更好?还有其他提高性能的想法吗?

编辑:解决方案:我尝试了给出的 2 个建议。

  1. 在我的列表理解中引用我的 Z 值,而不是在数组中进行两次查找,这需要更长的时间。
  2. 重写函数来处理numpy数组的问题

我重写了列表理解:

xyz = [[xllcornor + (col * cellsize),
               yllcornor + raster_size_y - (row * cellsize),
               val_z]
               for row in rows for col in cols for val_z in 
[asc_array[row, col]]
               if val_z != nodata_value]

numpy 函数变成了这样:

def asc_process_numpy_single(self, asc_array, asc_info, skip):
    # ncols = asc_info['ncols']
    nrows = asc_info['nrows']
    xllcornor = asc_info['xllcornor']
    yllcornor = asc_info['yllcornor']
    cellsize = asc_info['cellsize']
    nodata_value = asc_info['nodata_value']

    raster_size_y = cellsize*nrows
    # raster_size_x = cellsize*ncols

    rows = np.arange(0,asc_array.shape[0],skip)[:,np.newaxis]
    cols = np.arange(0,asc_array.shape[1],skip)

    x = np.zeros((len(rows),len(cols))) + xllcornor + (cols * cellsize)
    y = np.zeros((len(rows),len(cols))) + yllcornor + raster_size_y - (rows * 
    cellsize)
    z = asc_array[::skip,::skip]

    xyz = np.asarray([x,y,z]).T.transpose((1,0,2)).reshape( 
    (int(len(rows)*len(cols)), 3) )
    mask = (xyz[:,2] != nodata_value)
    xyz = xyz[mask]
    return xyz

我在 numpy 函数的最后两行添加了掩码,因为我不想要 nodata_values。性能按顺序如下;for 循环、列表理解、列表理解建议和 numpy 函数建议:

609 ms ± 44.8 ms per loop (mean ± std. dev. of 10 runs, 1 loop each)
706 ms ± 22 ms per loop (mean ± std. dev. of 10 runs, 1 loop each)
604 ms ± 21.5 ms per loop (mean ± std. dev. of 10 runs, 1 loop each)
70.4 ms ± 1.26 ms per loop (mean ± std. dev. of 10 runs, 1 loop each)

列表解析与优化时的 for 循环相比,但 numpy 函数以 9 倍加速聚会。

非常感谢您的意见和建议。我今天学到了很多。

标签: pythonperformancefor-looplist-comprehension

解决方案


我能想象的唯一让你慢下来的是,在原始代码中,你放入asc_array[row, col]了一个临时变量,而在列表理解中,你对它进行了两次评估。

您可能想尝试两件事:

  1. val_z使用海象运算符在“if”语句中分配值,或

  2. for val_z in [asc_array[row, col]]在其他两个fors之后添加。

祝你好运。


推荐阅读