arraysstridecache-locality

What is the difference in the Code Snippets?


I am a beginner in operating systems, and I am trying to understand some code snippets. Can you please explain to me the difference between these code snippets??

int sum_array_rows(int a[M][N])
 {
    int i,j,sum=0;
    for(i=0;i<M;i++)
      for(j=0;j<N;j++)
        sum+=a[i][j];
    return sum;
  }

and

int sum_array_col(int a[M][N])
 {
    int i,j,sum=0;
    for(i=0;i<N;i++)
      for(j=0;j<M;j++)
        sum+=a[i][j];
    return sum;
  }

The different parts are the double For attributes Is one of them supposed to be faster than the other?? If so can you please explain to me why, because I don't understand.


Solution

  • As others have said, the second code snippet can cause an overflow error if the array dimensions are not the same, so this issue would need to be fixed.

    However looping over the last array dimension in the inner-most loop can be faster than otherwise, due to how the elements of multidimensional arrays are stored in memory and the caching architectures of modern CPUs.

    The terms to search for here are 'cache locality' and 'stride of arrays'