#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

int main(int argc, char **argv) {
  int page_size;

  /* Get the system's page size */
  page_size = getpagesize();

  /* Parse arguments */
  if (argc != 3) {
    fprintf(stderr,"Usage: %s <span in pages> <time>\n",argv[0]);
    exit(1);
  }

  /* Parse the span command-line argument */
  int span;
  if (sscanf(argv[1],"%d",&span) != 1) {
    fprintf(stderr,"Invalid span\n");
    exit(1);
  } else if (span < 0) {
    fprintf(stderr,"Invalid span\n");
    exit(1);
  }

  /* Parse the time command-line argument */
  double max_elapsed;
  if (sscanf(argv[2],"%lf",&max_elapsed) != 1) {
    fprintf(stderr,"Invalid time\n");
    exit(1);
  } else if (max_elapsed < 0) {
    fprintf(stderr,"Invalid time\n");
    exit(1);
  }

  /* Allocate a big array */
  char *array = (char *)malloc(span * page_size * sizeof(char));
  if (array == NULL) {
    fprintf(stderr,"out of memory\n");
    exit(1);
  }

  /* Get the current time */
  struct timeval begin, now;
  gettimeofday(&begin,NULL);
  double elapsed = 0;
  
  /* Loop for the required amount of time */
  int count = 0; // in millions
  while (elapsed < max_elapsed) {
    int index,i;
     
    /* Do a million random accesses */
    for (i = 0; i < 1000000; i++) {
      index = rand() % (span * page_size); 
      array[index] = i;
    }
    count ++;
    
    /* Update the slapsed time */
    gettimeofday(&now,NULL);
    elapsed  = ((now.tv_sec - begin.tv_sec) * 1000000.0 + 
                  now.tv_usec - begin.tv_usec) / 1000000.00;
  }

  fprintf(stdout,"span=%d, Mtrans/sec=%.3f\n",span,count / elapsed);
  exit(0); 


}
