(c++)使用相同的代码以4种不同的方式遍历数组

(c++) Going through an array in 4 different ways with the same code

本文关键字:4种 方式 遍历 数组 代码 c++      更新时间:2023-10-16

我正在2D阵列上进行一些计算,需要以4种不同的方式遍历阵列

for(int i=0; i < array_size; i++) {
   for(int j=0; j < array_size; j++) {
      #do some computation around [i][j] element
   }
}
for(int i = array_size - 1; i >= 0; i--) {
   for(int j=0; j < array_size; j++) {
      #do the same computation around [i][j] element
   }
}

for(int i=0; i < array_size; i++) {
   for(int j=array_size - 1; j >= 0; j--) {
      #do the same computation around [i][j] element
   }
}

for(int i = array_size - 1; i >=0; i--) {
   for(int j = array_size - 1; j >= 0; j--) {
      #do the same computation around [i][j] element
   }
}

问题是,首先,计算的代码很长,将来也可能会更改。其次,阵列很大,因此性能也是一个问题。

我一直想知道是否有任何方法可以避免代码重复并保持性能。由于将代码提取到函数中可能会降低性能。

如果使用内联函数,编译器很可能会为您执行内联,从而为您提供所需的结果。

inline void work(int i, int j) { ... }

如果你想对此更加科学,并且这个函数需要花费大量的时间,那么我建议你投资一个探查器。在开源方面,有些人会推荐gprof。在专有方面,有些人(包括我自己)会推荐英特尔的VTune。