用于交换二维数组的C++执行时间



如果存储为向量,为什么哪个维度更大很重要?我使用这样的代码,不明白为什么第二部分给出更大的结果时间。

#include <time.h>
#include <iostream>
#include <random>
using namespace std;

const int n=2000000,m=10;
const int n1=10,m1=2000000;
int a[n][m];
int b[n][m];
int aa[n1][m1];
int bb[n1][m1];
int main()
{
time_t start,end;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
a[i][j]=rand()%(m*n);
b[i][j]=rand()%(m*n)+m*n;
}
start = clock(); // from here
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
int tmp = a[i][j];
a[i][j] = b[i][j];
b[i][j] = tmp;
}
end = clock(); // to here
cout<<end-start<<endl;
for(int i = 0; i < n1; i++)
for(int j = 0; j < m1; j++)
{
aa[i][j]=rand()%(m1*n1);
bb[i][j]=rand()%(m1*n1)+m1*n1;
}
start = clock(); // from here
for(int i = 0; i < n1; i++)
for(int j = 0; j < m1; j++)
{
int tmp = aa[i][j];
aa[i][j] = bb[i][j];
bb[i][j] = tmp;
}
end = clock(); // to here
cout<<end-start<<endl;
return 0;
}

第一个cout我得到了~69,第二个cout得到了~172,而我希望它们是一样的,因为它们使用相同操作的次数相同

附言:我使用带有标志的g++来遵循C++11 ISO C++语言标准,这是唯一在编译器设置中打开的标准

1有问题的错误

我的第一名和第二名分别是113000096000。我认为你的问题顺序错了=>所以评论中的答案很复杂。

2说明

如果是这种情况:[20000000][10]数组的循环速度比[10][2000000]数组慢
这更有意义:在情况2中,内部循环是在连续的内存位置上循环,并且可以缓存该内存(数组行((实际上像L1一样缓存(,然后内存访问速度会快得多。

3如何得出答案

也就是说:欢迎来到StackOverflow
达到这种答案的最好方法是一定不要退步!

  1. 创建一个可复制的示例=>你的问题做得很好(所以我可以复制粘贴(
  2. 在命令行中播放(例如:C11标志不是必需的g++ -O0 array.c && ./a.out就足够了[注意-O0可以防止优化,所以代码正在运行](。用CCD_ 3和CCD_。尽可能发表评论。请注意,原始循环的时间完全相同(对我来说是64636个刻度(。如果注释任何行(循环中(
for(int i = 0; i < n1; i++)
for(int j = 0; j < m1; j++)
{
// int tmp = aa[i][j];
// aa[i][j] = bb[i][j];
// bb[i][j] = tmp;
}

取消注释一个内存读取(int tmp = aa[i][j]表示REGISTER<-MEMBORY表示读取。

  1. 注意您的结果在玩时:
| Array  Operation | Crude Loop | Read  | Copy  | Full |
| ---               | ---        | ---   | ---   | --- |
| [2000000][10]     | 60083      | 79813 | 79287 | 131311 |
| [10][2000000]     | 54707      | 63893 | 72254 | 100002 |

因此,在第一个[200000000][10]数组中,每次读取都会得到9.8e-4个ticks,在第二个数组中得到4.6e-4(速度快两倍(。

  1. 带着这些结果环游世界,从中获得答案

这或多或少就是你所做的,答案(我重复一遍(是由于在数组行中缓存连续内存位置

最新更新