/* allocate.c */


/* Include Files */
#include <time.h>
#include <stdio.h>

clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP  if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf( "%6.3f seconds used by the processor.", \
                  ((double)stopm-startm)/CLOCKS_PER_SEC);

void memexperiment( int, int);

main(int argc, char *argv[])
{
  int rows, cols;

  if (argc != 3) {
	  printf("Usage: allocate <rows> <cols>\n");
	  exit(1);
  }
  rows = atoi(argv[1]);
  if ( (rows > 20000) || (rows < 1)) {
	  printf("Number of rows must be between 1 and 20000.\n");
	  exit(1);
  }
  cols = atoi(argv[2]);
  if ( (cols > 20000) || (cols < 1)) {
	  printf("Number of columns must be between 1 and 20000.\n");
	  exit(1);
  }

  memexperiment(rows, cols);
}

void memexperiment( int ROWS, int COLS )
{
  int * * arrayptr;
  int i, j;

  printf("Starting to malloc.\n");
  START;
  arrayptr = (int * *) malloc(ROWS*sizeof( int * ) );
  if (arrayptr == NULL) {printf("malloc failed, num rows=%d\n",i); exit(1);}
  for(i=0;i<ROWS;i++)
    {
      arrayptr[i] = (int *) malloc(COLS*sizeof(int));
      if (arrayptr[i] == NULL) {printf("malloc failed, row=%d\n",i); exit(1);}
    }
  STOP;
  PRINTTIME;
  printf("\nEnd of malloc \n");

  printf("Starting to access the array one row at a time.\n");
  START;
  for(i=0;i<ROWS;i++)
  {
    for(j=0;j<COLS;j++)
	{	
	  arrayptr[i][j] = i;
	}
  }
  STOP;
  PRINTTIME;
  printf("\nEnd of row access.\n");

  printf("Starting to access the array one column at a time.\n");
  START;
  for(j=0;j<COLS;j++)
    {
      for(i=0;i<ROWS;i++)
	{
	  arrayptr[i][j] = i;
	}
  }
  STOP;
  PRINTTIME;
  printf("\nEnd of column access.\n");

  printf("Starting to free the array.\n");
  START;
  for(i=0;i<ROWS;i++)
    {
      free(arrayptr[i]);
    }
  STOP;
  PRINTTIME;
  printf("\nEnd of free.\n");
}
