📚 The CoCalc Library - books, templates and other resources
License: OTHER
/******************************************************************1* CACHE project *2* *3* Using this program, on as many different kinds of computers as *4* possible, investigate these cache parameters: *5* -- total cache size *6* -- cache width *7* -- cache replacement policy *8******************************************************************/910/* I got this program from Brian Harvey, who teaches CS61C at11Berkeley. He didn't put a copyright on it, but he should12at least get credit for it. Thanks, Brian! */1314#include <stdio.h>15#include <unistd.h>16#include <sys/times.h>17#include <sys/types.h>18#include <time.h>1920#define CACHE_MIN (32*1024) /* smallest cache */21#define CACHE_MAX (32*1024*1024) /* largest cache */22#define SAMPLE 10 /* to get a larger time sample */2324int x[CACHE_MAX]; /* array going to stride through */25long clk_tck;2627double get_seconds() { /* routine to read time */28struct tms rusage;29times(&rusage); /* UNIX utility: time in clock ticks */30return (double) (rusage.tms_utime)/clk_tck;31}3233int main() {34int register i, index, stride, limit, temp;35int steps, tsteps, csize;36double sec0, sec; /* timing variables */3738clk_tck = sysconf(_SC_CLK_TCK);3940for (csize=CACHE_MIN; csize <= CACHE_MAX; csize=csize*2)41for (stride=1; stride <= csize/2; stride=stride*2) {42sec = 0; /* initialize timer */43limit = csize-stride+1; /* cache size this loop */4445steps = 0;46do { /* repeat until collect 1 second */47sec0 = get_seconds(); /* start timer */48for (i=SAMPLE*stride;i!=0;i=i-1) /* larger sample */49for (index=0; index < limit; index=index+stride)50x[index] = x[index] + 1; /* cache access */51steps = steps + 1; /* count while loop iterations */52sec = sec + (get_seconds() - sec0);/* end timer */53} while (sec < 1.0); /* until collect 1 second */5455/* Repeat empty loop to loop subtract overhead */56tsteps = 0; /* used to match no. while iterations */57do { /* repeat until same no. iterations as above */58sec0 = get_seconds(); /* start timer */59for (i=SAMPLE*stride;i!=0;i=i-1) /* larger sample */60for (index=0; index < limit; index=index+stride)61temp = temp + index; /* dummy code */62tsteps = tsteps + 1; /* count while iterations */63sec = sec - (get_seconds() - sec0);/* - overhead */64} while (tsteps<steps); /* until = no. iterations */6566printf("Size: %7ld Stride: %7ld read+write: %4.4lf ns\n",67csize*sizeof(int), stride*sizeof(int),68(double) sec*1e9/(steps*SAMPLE*stride*((limit-1)/stride+1)));69}; /* end of both outer for loops */70}71727374