1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
#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);
   }
}