Skip to content
BIASED
Back to topic

Optional

Direct-mapped cache hit/miss trace

On an address trace compute tag/index/offset; mark hit/miss and conflict victim.

Version
v2
Minutes
~25
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

CA · Direct-mapped кэш: hit/miss / Direct-mapped cache hit/miss

Activity version: 2 · Seed: n/a · Данные: topic field-split example 0x1234ABCD (b=s=6b=s=6) plus a tiny direct-mapped trace (B=16B=16, S=4S=4, E=1E=1).

Compute tag / index / offset; mark hit/miss and the conflict victim tag.

Ожидаемые числа
Case Result
0x1234ABCD, b=s=6b=s=6 offset 1313, index 4747, tag 0x1234A
trace hits / misses 11 hit, 55 misses
conflict victim on 0x40 tag 00
Самопроверка в ноутбуке

Активность не входит в процент освоения.

import numpy as np
 
 
def split_addr(addr: int, b: int, s: int):
    offset = addr & ((1 << b) - 1)
    index = (addr >> b) & ((1 << s) - 1)
    tag = addr >> (b + s)
    return tag, index, offset
 
 
tag, index, offset = split_addr(0x1234ABCD, 6, 6)
print("fields", hex(tag), index, offset)
assert offset == 13
assert index == 47
assert tag == 0x1234A
 
# Tiny direct-mapped cache: B=16 (b=4), S=4 (s=2), E=1
b, s = 4, 2
valid = np.zeros(1 << s, dtype=bool)
tags = np.full(1 << s, -1, dtype=int)
trace = [0x00, 0x04, 0x40, 0x08, 0x44, 0x10]
events = []
for addr in trace:
    tag, index, offset = split_addr(addr, b, s)
    hit = bool(valid[index] and tags[index] == tag)
    victim = int(tags[index]) if (valid[index] and not hit) else None
    if not hit:
        valid[index] = True
        tags[index] = tag
    events.append({"addr": addr, "tag": tag, "index": index, "hit": hit, "victim": victim})
 
hits = sum(1 for e in events if e["hit"])
misses = len(events) - hits
print("events", events)
print("hits", hits, "misses", misses)
assert hits == 1 and misses == 5
assert events[0]["hit"] is False and events[0]["victim"] is None  # cold
assert events[1]["hit"] is True  # same block
assert events[2]["addr"] == 0x40 and events[2]["hit"] is False and events[2]["victim"] == 0
assert events[3]["hit"] is False and events[3]["victim"] == 1
print("OK: direct-mapped hit/miss")
 
Самопроверка в ноутбуке
  • 0x1234ABCD → offset 13, index 47, tag 0x1234A
  • трасса: 1 hit / 5 miss
  • на 0x40 жертва — tag 0