(c++)使用相同的代码以4种不同的方式遍历数组
(c++) Going through an array in 4 different ways with the same code
我正在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。
相关文章:
- 在C++中将函数压缩为两种方式
- 哪种方式更快?究竟发生了什么,我们没有看到什么?
- 将函数作为参数传递的两种方式之间的区别
- 初始化结构的两种方式
- !=的另一种方式
- 以一种方式使用字符串选择(如果语句)
- 这两种方式有什么区别吗?
- 在 OpenGL 中渲染对象的哪种方式更有效
- 在哪种方式搜索容器中的元素的方式更有效
- 一种方式链接列表和不需要的第一个元素AFRTER填充
- 由于您可以在C 中以两种方式声明复制构造函数,这是正确的方式
- 重载输入/输出运算符,为什么它以这种方式工作而不是以另一种方式工作
- 哪种方式将 HHOOK 消息返回到系统更好
- 哪种方式更快
- 哪种方式更好地获得64位整数中较低的32位
- 是 2s 补码存储负数的一种方式
- 尝试在Qt中连接隐藏信号的两种方式之间做出决定
- C++课间交流2种方式
- 哪种方式更适合定义类型特征或行为
- 哪种方式更适合阵列访问