The TLB is a small cache of page-table entries. A hit costs one TLB lookup plus one memory access; a miss costs the TLB lookup, a page-table read and the memory access.
What to build
Run a list of page references through a TLB with FIFO replacement, and compute the average access time.
Requirements
- The TLB has
centries and starts empty. For each reference: if the page is in the TLB it is a hit and costst + m. Otherwise it is a miss and costst + 2m, and the page is put in the TLB, in a free entry if there is one, else in place of the entry that has been there longest (FIFO). - Print
hits H,misses Mandaverage time Awith 2 decimal places, whereAis the total cost divided byn.
Input
The first line has c (1 ≤ c ≤ 8), t and m (1 ≤ t ≤ 100, 1 ≤ m ≤ 1000) and n (1 ≤ n ≤ 100). The second line has the n page numbers (0 to 99).
Output
Three lines: hits H, misses M, average time A.
Constraints
n is never a multiple of 8 in the tests, so no average ends in an exact tie when rounded.
Example
Input:
2 20 100 5
1 2 1 2 3
Output:
hits 2
misses 3
average time 180.00
Why it works
Every miss costs one extra memory access, so the average rises as the hit rate falls. A program that loops over a few pages keeps them in the TLB and almost always hits, which is why even a tiny TLB speeds up memory so much.
Examples
2 20 100 5 1 2 1 2 3
hits 2 misses 3 average time 180.00
3 10 50 6 4 4 4 4 4 4
hits 5 misses 1 average time 68.33
Hints
Hint 1
Keep the TLB as an array of c pages (empty at the start, -1) and an index of the next entry to replace, like FIFO page replacement.
Hint 2
A hit costs t + m. A miss costs t + 2m, then the page goes into the TLB: into the next entry in FIFO order.
Hint 3
Add up all the costs and divide by n as doubles; print with %.2f.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int c, t, m, n, tlb[8], next = 0, hits = 0, page;
long total = 0;
scanf("%d %d %d %d", &c, &t, &m, &n);
for (int i = 0; i < c; i++) tlb[i] = -1;
for (int i = 0; i < n; i++) {
scanf("%d", &page);
int hit = 0;
for (int j = 0; j < c; j++)
if (tlb[j] == page) hit = 1;
if (hit) {
hits++;
total += t + m;
} else {
total += t + 2 * m;
tlb[next] = page;
next = (next + 1) % c;
}
}
printf("hits %d\n", hits);
printf("misses %d\n", n - hits);
printf("average time %.2f\n", (double)total / n);
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step