If I run the following program and then run it again after swapping of i and j in sum+=arr[i][j], the execution time is very different i.e. 9.8 secs compared to 2.7 secs for before the swap. I just cannot understand why it is like this. Can someone please give me any idea about why it is so?
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
int long sum=0;
int size = 1024;
clock_t start, end;
double msecs;
start = clock();
int **arr = new int*[size];
for (int i = 0; i < size; i++)
{
arr[i] = new int[size];
}
for(int kk=0; kk<1000; kk++)
{
sum = 0;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size ; j++)
{
sum += arr[i][j];
}
}
}
end = clock();
msecs = ((double) (end - start)) * 1000 / CLOCKS_PER_SEC;
cout<<msecs<<endl<<endl;
return 0;
}