Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132929 views
License: OTHER
1
/******************************************************************
2
* CACHE project *
3
* *
4
* Using this program, on as many different kinds of computers as *
5
* possible, investigate these cache parameters: *
6
* -- total cache size *
7
* -- cache width *
8
* -- cache replacement policy *
9
******************************************************************/
10
11
/* I got this program from Brian Harvey, who teaches CS61C at
12
Berkeley. He didn't put a copyright on it, but he should
13
at least get credit for it. Thanks, Brian! */
14
15
#include <stdio.h>
16
#include <unistd.h>
17
#include <sys/times.h>
18
#include <sys/types.h>
19
#include <time.h>
20
21
#define CACHE_MIN (32*1024) /* smallest cache */
22
#define CACHE_MAX (32*1024*1024) /* largest cache */
23
#define SAMPLE 10 /* to get a larger time sample */
24
25
int x[CACHE_MAX]; /* array going to stride through */
26
long clk_tck;
27
28
double get_seconds() { /* routine to read time */
29
struct tms rusage;
30
times(&rusage); /* UNIX utility: time in clock ticks */
31
return (double) (rusage.tms_utime)/clk_tck;
32
}
33
34
int main() {
35
int register i, index, stride, limit, temp;
36
int steps, tsteps, csize;
37
double sec0, sec; /* timing variables */
38
39
clk_tck = sysconf(_SC_CLK_TCK);
40
41
for (csize=CACHE_MIN; csize <= CACHE_MAX; csize=csize*2)
42
for (stride=1; stride <= csize/2; stride=stride*2) {
43
sec = 0; /* initialize timer */
44
limit = csize-stride+1; /* cache size this loop */
45
46
steps = 0;
47
do { /* repeat until collect 1 second */
48
sec0 = get_seconds(); /* start timer */
49
for (i=SAMPLE*stride;i!=0;i=i-1) /* larger sample */
50
for (index=0; index < limit; index=index+stride)
51
x[index] = x[index] + 1; /* cache access */
52
steps = steps + 1; /* count while loop iterations */
53
sec = sec + (get_seconds() - sec0);/* end timer */
54
} while (sec < 1.0); /* until collect 1 second */
55
56
/* Repeat empty loop to loop subtract overhead */
57
tsteps = 0; /* used to match no. while iterations */
58
do { /* repeat until same no. iterations as above */
59
sec0 = get_seconds(); /* start timer */
60
for (i=SAMPLE*stride;i!=0;i=i-1) /* larger sample */
61
for (index=0; index < limit; index=index+stride)
62
temp = temp + index; /* dummy code */
63
tsteps = tsteps + 1; /* count while iterations */
64
sec = sec - (get_seconds() - sec0);/* - overhead */
65
} while (tsteps<steps); /* until = no. iterations */
66
67
printf("Size: %7ld Stride: %7ld read+write: %4.4lf ns\n",
68
csize*sizeof(int), stride*sizeof(int),
69
(double) sec*1e9/(steps*SAMPLE*stride*((limit-1)/stride+1)));
70
}; /* end of both outer for loops */
71
}
72
73
74