/* this is a sample program which finds maximum and calculates the execution time */ /* compilation: cc filename.c -lm -o filename running: filename help: man cc -- c compiler man times -- timing routine man vi -- full screen editor man dbx -- c debugger Refer to this handout or a unix and/or a C book, if needed. */ /*------------------- Include Files ------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/times.h> #include <sys/param.h> #include <sys/types.h> /*------------- Constants -----------------*/ #define maxSize 1024 /* max array size */ #define seed 10 /* seed for random number generator */ #define loop 1000 /* repeats loop times for timing accuracy */ main() { struct tms buffer; /* needed for timing function */ double StartTime, EndTime, ElapseTime; int A[maxSize]; /* input array */ int max; /* variable to contain the current maximum */ int i,j; /* index variables */ srand(seed); /* initialize random number generator */ for (i=0; i<maxSize; i++) A[i] = rand() % 1000; /* fill A with random number in the range 0 through 999; % is mod function */ StartTime = times(&buffer); /* get current time */ for (j=1; j<=loop; j++) { /* repeat max-finding 1000 times so that the time taken would be large enough to measure */ max = A[0]; /* initialize max */ for (i=1; i < maxSize; i++) { if (max < A[i]) max = A[i]; } } EndTime = times(&buffer); /* current time */ ElapseTime = EndTime - StartTime; ElapseTime = ElapseTime / loop; /* time for a single run */ ElapseTime = ElapseTime / HZ; /* to convert into seconds */ printf("Max = %d, time taken = %f seconds \n", max, ElapseTime); }