ECE 3600 - Assignment P19 - Due: 8 October 2022


Write a C program to measure the effect of caching on 2D integer array indexing by timing access by rows vs. access by columns.

The array should be allocated with 300 rows. Each row of the 2D array should occupy one page of memory, so the number of columns depends on the page size:

  #include <unistd.h>
  #include <stdlib.h>
  ...
  int main( void)
  {
    int nrows = 300, PAGESIZE = sysconf(_SC_PAGESIZE), ncols = PAGESIZE/sizeof(int);

    int *a = calloc( nrows*ncols, sizeof(int));
Note that a dynamically allocated 2D array is stored as a 1D array, so a[row][col] is really a[row*ncols+col]

Measure the time in msec that it takes to perform 100 iterations of each of the following accesses:

   // by rows
   //
    for( int row = 0; row < nrows; ++row)
      for( int col = 0; col < ncols; ++col)
        a[row*ncols+col] += 1;
and:
   // by cols
   //
    for( int col = 0; col < ncols; ++col)
      for( int row = 0; row < nrows; ++row)
        a[row*ncols+col] += 1;
Include the program output in a comment at the end of the code.

References:   sysconf(), calloc(), msec();   getconf


Upload source files

Programs must compile with no warnings or errors using: gcc -Wall

Each source file must start with a comment containing your name and a description.