/* Uses sequential accesses to determine cache size * By P. Koopman for CMU 18-742 Spring 1998 * Also used for CMU 18-548 Fall 1998 * * Note: this program is not *guaranteed* to work on * all platforms -- use common sense to make sure the * results you are getting are appropriate * Also, major changes will have to be made to conform * to the requirements of the homework solution. */ #include #include #define HZ 60 #include #include #define K * 1024 #define M * 1024 * 1024 /* Tune TUNE for machine speed; larger number runs slower */ #define TUNE 1 M #define MAXSIZE (10 K) /* it's easy to cash a check, but hard to check a cache */ int touch_array(int *array, int num_ints, int iterations) { int i; int sum=0; int *p, *limit; limit = &(array[num_ints-1]); for (i = 0; i < iterations; i++) { /* touch elements; pointer match results in faster code */ for (p = array; p != limit; p++) { sum += *p; } } return(sum); } void main(void) { int *a; /* data array */ int size, j, iter; int num_ints; /* number of ints in the array */ int result; double x, elapsed, rate; struct tms time_info; long Begin_Time, End_Time; printf("\n\nTesting tuning value of %d\n", TUNE); printf("Array size, Iterations, seconds, bytes/sec\n"); for (size = 1 K; size < MAXSIZE; size += 1 K ) { a = (int *) malloc(size); num_ints = size / sizeof(int); /* initialize array to a constant value */ for (j = 0; j < num_ints; j++) { a[j] = 1; } /* scale iterations with array size, so run time is about constant */ x = size; x = (TUNE) / x; iter = x * 100; /* pre-load cache to avoid compulsory misses */ result = touch_array(a, num_ints, 1); /* start timer */ printf("%9d, %10d, ", size, iter); times (&time_info); Begin_Time = (long) time_info.tms_utime; /* touch the array repeatedly */ result += touch_array(a, num_ints, iter); /* stop timer */ times (&time_info); End_Time = (long) time_info.tms_utime; elapsed = ((double) (End_Time - Begin_Time) ) / HZ ; rate = size; rate = rate * iter / elapsed; /* make print conditional on non-zero result to foil * global optimizers (result will always be non-zero) */ if (result) printf("%.3f, %.f\n", elapsed, rate); free(a); } /* next bigger array size */ }