Перейти к содержимому
BIASED
К теме

По желанию

Direct-mapped кэш: hit/miss трасса

На трассе адресов посчитать tag/index/offset; отметить hit/miss и жертву при конфликте.

Версия
v2
Минут
~25
Проверка
Самопроверка в ноутбуке

Пока нет автопроверки на платформе: сравните вывод ячеек с ожидаемыми числами в ноутбуке. Это не долг и не влияет на процент освоения.

Скачать .ipynb

Скачайте ноутбук и запустите его локально. Требования к окружению указаны внутри.

Содержимое ноутбука

Можно прочитать с телефона. Код ниже не выполнялся в браузере; для запуска скачайте ноутбук.

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