C   24

cachsize.c

Guest on 15th January 2022 09:16:07 AM

  1. /* Uses sequential accesses to determine cache size * By P. Koopman for CMU 18-742 Spring 1 * Also used for CMU 18-548  * * 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, some minor changes will have to be made to conform * to the requirements of the homework solution. */
  2.  #include <sys/times.h>
  3. #include <sys/types.h>
  4.  #define HZ 60
  5.  #include <stdio.h>
  6. #include <stdlib.h>
  7.  #define K * 1024 #define M * 1024 * 1024
  8. /* Tune TUNE for machine speed; larger number runs slower */
  9.  #define TUNE 1 M #define MAXSIZE (10 K)
  10. /* it's easy to cash a check, but hard to check a cache */
  11.  int touch_array(int *array, int num_ints, int iterations) {
  12. int i;
  13.  int sum=0;
  14.  int *p, *limit;
  15.  limit = &(array[num_ints-1]);
  16. for (i = 0; i < iterations; i++) {
  17.  /* touch elements; pointer match results in faster code */
  18.  for (p = array; p != limit; p++) { sum += *p; } } return(sum);
  19. } void main(void) { int *a;
  20. /* data array */
  21.  int size, j, iter;
  22.  int num_ints;
  23.  /* number of ints in the array */
  24.  int result;
  25.  double x, elapsed, rate;
  26.  struct tms time_info;
  27. long Begin_Time, End_Time;
  28.  printf("\n\nTesting tuning value of %d\n", TUNE);
  29. printf("Array size, Iterations, seconds, bytes/sec\n");
  30.  for (size = 1 K; size < MAXSIZE; size += 1 K ) { a = (int *) malloc(size);
  31. num_ints = size / sizeof(int); /* initialize array to a constant value */
  32.  for (j = 0; j < num_ints; j++) { a[j] = 1; }
  33. /* scale iterations with array size, so run time is about constant */
  34.  x = size; x = (TUNE) / x; iter = x * 100;
  35. /* pre-load cache to avoid compulsory misses */ result = touch_array(a, num_ints, 1); /*
  36.  start timer */ printf("%9d, %10d, ", size, iter); times (&time_info); Begin_Time = (long) time_info.tms_utime; /*
  37. touch the array repeatedly */
  38. result += touch_array(a, num_ints, iter);
  39.  /* stop timer */ times (&time_info); End_Time = (long) time_info.tms_utime; elapsed = ((double) (End_Time - Begin_Time) ) / HZ ;
  40. rate = size; rate = rate * iter / elapsed;
  41. /* 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); } /*
  42.  next bigger array size */
  43. }

Raw Paste


Login or Register to edit or fork this paste. It's free.