Count misses and invalidations

With write-invalidate coherence, a write removes the block from the other caches, so they must miss when they use it again. Count these effects for a series of accesses.

What to build

A program that simulates the private caches of several cores and counts misses and invalidations.

Requirements

  • Each core has a cache big enough to hold every block it uses (no evictions). All caches start empty.
  • A read by a core misses if the core does not hold the block; then it holds it. A write misses in the same way, and it also removes the block from every other core's cache, counting one invalidation for each core that held it.
  • Print misses M and invalidations I.

Input

A line with the number of cores c, a line with n, then n lines R core block or W core block.

Output

Two lines.

Constraints

1 ≤ c ≤ 8; 1 ≤ n ≤ 200; cores are numbered from 0; blocks are numbers from 0 to 100.

Example

Input:

2
5
R 0 7
R 1 7
W 0 7
R 1 7
W 1 7

Output:

misses 3
invalidations 2

Why it works

A copy lives in a cache until another core writes the block. Each such removal is an invalidation, and the next access by the core that lost its copy is a coherence miss, which shows what sharing costs.

Examples

Example 1 · Input
2
5
R 0 7
R 1 7
W 0 7
R 1 7
W 1 7
Expected output
misses 3
invalidations 2
Example 2 · Input
1
3
R 0 1
W 0 1
R 0 2
Expected output
misses 2
invalidations 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep one set of blocks for each core.

Hint 2

On any access, if the core does not hold the block, count a miss and add the block. On a write also remove the block from every other core, counting one invalidation for each core that had it.

Solution

Show one correct solution (try it yourself first)
c = int(input())
n = int(input())
held = [set() for _ in range(c)]
misses = inval = 0
for _ in range(n):
    op, core, block = input().split()
    core, block = int(core), int(block)
    if block not in held[core]:
        misses += 1
        held[core].add(block)
    if op == "W":
        for o in range(c):
            if o != core and block in held[o]:
                held[o].discard(block)
                inval += 1
print("misses", misses)
print("invalidations", inval)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Cache coherence and the MESI protocol →