Source

hack2 / bench / numeric / arrloop.c


/* 3 args - array size, number of iterations, number of scenario
   Scenarios:
   0 - a + b
   1 - a + (b + c)
   2 - (a + b) + ((c + d) + e)
 */

#include <stdio.h>
#include <stdlib.h>

double sum(int size, double *res)
{
  int i;
  double s;
  for (i = 0; i < size; ++i)
    s += res[i];
  return s;
}

#define FILENAME "/tmp/a.data"

void init_file(int size, double *arr)
{
  int i;
  int count = 0;
  FILE* f = fopen(FILENAME, "r");
  while (count < size) {
    count += fread(arr + count, 1, size - count, f);
  }
  fclose(f);
}

void init(int size, double *arr, double what)
{
  int i;
  int count;
  for (i = 0; i < size; ++i)
    arr[i] = what;
}

void add(int size, double *a, double *b, double *res)
{
  int i;
  for (i = 0; i < size; i++)
    res[i] = res[i] + a[i] + b[i];
}

double* new_arr(int size, double what)
{
  double *a;
  a = (double*)malloc(sizeof(double) * size);
  if (what == -1) {
    init_file(size, a);
  } else {
    init(size, a, what);
  }
  return a;
}

int main(int argc, char **argv)
{
  double *a, *b, *res, *c, *d, *e, *tmp1, *tmp2, *tmp3;
  int size = atoi(argv[1]);
  int bench = atoi(argv[3]);
  int i, k;
  double what;
  double s;
  int n = atoi(argv[2]);
  a = new_arr(size, -1);
  b = new_arr(size, -1);
  c = new_arr(size, -1);
  d = new_arr(size, -1);
  e = new_arr(size, -1);
  res = new_arr(size, 0);
  for (i = 0; i < n; ++i) {
    if (bench == 0) {
      for (k = 0; k < size; k++) {
        res[k] = (a[k] + b[k]);
      }
    } else if (bench == 1) {
      for (k = 0; k < size; k++) {
        res[k] = (a[k] + b[k]) + c[k];
      }
    } else if (bench == 2) {
      for (k = 0; k < size; k++) {
        res[k] = (a[k] + b[k]) + ((c[k] + d[k]) + e[k]);
      }
    }
  }
  s = sum(size, res);
  printf("%f\n", s);
}