Sample solution

Content

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/times.h>
#include <unistd.h>

/* return real time in seconds since start of the process */
double walltime() {
   static int ticks_per_second = 0;
   if (!ticks_per_second) {
      ticks_per_second = sysconf(_SC_CLK_TCK);
   }
   struct tms timebuf;
   /* times returns the number of real time ticks passed since start */
   return (double) times(&timebuf) / ticks_per_second;
}

void init_vector(double* v, size_t len, ptrdiff_t incr) {
   for (size_t i = 0; i < len; ++i) {
      v[i*incr] = i + 1;
   }
}

void print_vector(double* v, size_t len, ptrdiff_t incr) {
   for (size_t i = 0; i < len; ++i) {
      printf(" %4.1lf", v[i*incr]);
   }
   printf("\n");
}

#define MAX_LEN 134217728

int main() {
   double* x; double* y; // two vectors living in the space of "vector"
   double t0, t1, t2; // time stamps
   printf("     len t1 (separate) t2 (interleaving)      t2/t1\n");
   for (size_t len = 8192; len <= MAX_LEN/2; len *= 2) {
      printf("%8zd", len);

      /* separate vectors */
      double* vector1 = malloc(sizeof(double) * len * 2);
      x = vector1;
      y = vector1 + len;
      t0 = walltime();
      init_vector(x, len, 1);
      init_vector(y, len, 1);
      t1 = walltime() - t0;
      printf(" %12.2lf", t1);

      /* interleaved vectors */
      double* vector2 = malloc(sizeof(double) * len * 2);
      t0 = walltime();
      x = vector2; y = vector2 + 1;
      init_vector(x, len, 2);
      init_vector(y, len, 2);
      t2 = walltime() - t0;
      printf(" %12.2lf %16.2lf", t2, t2/t1);
      printf("\n");

      free(vector1); free(vector2);
   }
}

Compilation and Execution

theon$ gcc -Wall -o example3_vector example3_vector.c
theon$ ./example3_vector
     len t1 (separate) t2 (interleaving)      t2/t1
    8192         0.00         0.00             -NaN
   16384         0.00         0.00             -NaN
   32768         0.00         0.01              Inf
   65536         0.00         0.00             -NaN
  131072         0.00         0.01              Inf
  262144         0.00         0.01              Inf
  524288         0.01         0.03             3.00
 1048576         0.01         0.04             4.00
 2097152         0.02         0.05             2.50
 4194304         0.04         0.11             2.75
 8388608         0.07         0.22             3.14
16777216         0.11         0.35             3.18
33554432         0.22         0.69             3.14
67108864         0.43         1.40             3.26
theon$