【问题标题】:Is there a fast way to loop around a 2d array's boarder/edge?有没有一种快速的方法来循环二维数组边界/边缘?
【发布时间】:2013-05-01 08:21:35
【问题描述】:

如问题所示。我正在做一个任务,其中边界被定义为某个数字,而内部 2d 数组需要一些计算。我写道:

 for(int col = 0; col < this.w; col++){
    energyMatrix[0][col]  = 195075;
    energyMatrix[this.h-1][col] = 195075;
 }
 for(int row = 1; row < this.h - 1; row++){
    energyMatrix[row][0] =  195075;
    energyMatrix[row][this.w-1] = 195075;
 }

但是还有另一种(更快的)方法可以做到这一点吗?

【问题讨论】:

  • 不——没关系,这部分代码可能不是瓶颈——它通常是需要优化的内部处理,如果有的话。

标签: loops multidimensional-array


【解决方案1】:

可能有许多不同的方法可以实现相同的目标,如果您只是告诉我们您实际使用哪种语言进行编码 :-) 您所拥有的适用于 (至少)C、C++ 和 Java。

但是,它们中的任何一个都不太可能快比你那里的。如果您更多地考虑宏级别(例如算法选择、缓存等)而不是这个级别的细节,则更有可能获得更好的性能改进。


您可以尝试的一件事,虽然我仍然认为它的改进值得怀疑,但是通过在第一个循环中做更多的工作来最小化第二个循环的大小:

if (this.h >= this.w) {
    for (int i = 0; i < this.w; i++) {
        energyMatrix[0][i]  = 195075;
        energyMatrix[this.h-1][i] = 195075;
        energyMatrix[i][0] =  195075;
        energyMatrix[i][this.w-1] = 195075;
    }
    for (int i = this.w + 1; i < this.h; i++) {
        energyMatrix[i][0] =  195075;
        energyMatrix[i][this.w-1] = 195075;
    }
} else {
    for (int i = 0; i < this.h; i++) {
        energyMatrix[i][0] =  195075;
        energyMatrix[i][this.w-1] = 195075;
        energyMatrix[0][i]  = 195075;
        energyMatrix[this.h-1][i] = 195075;
    }
    for (int i = this.h + 1; i < this.w; i++) {
        energyMatrix[0][i]  = 195075;
        energyMatrix[this.h-1][i] = 195075;
    }
}

这可能会消除运行循环中的一些代码开销,但正如我所说,我认为您不会从中获得预期的性能改进。

并且,与所有优化尝试一样,您应该衡量,而不是猜测!使用真实数据进行尝试,如果收益不超过成本(更复杂的代码),则放弃它。

【讨论】:

    猜你喜欢
    • 2018-02-05
    • 2021-04-17
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    相关资源
    最近更新 更多