第三次查是命中还是未命中
某名字 TTL 是 60。第 0 秒查一次、第 70 秒再查一次,第 70 秒这次是命中还是未命中?
贯穿本节的 TTL 缓存:query(cache, 名字, ip, now, ttl) 查一次——缓存里有且没过期(now-存入时刻 < ttl)就交回 hit,否则把它记进缓存(回填)并交回 miss。hits(事件表) 按顺序查一串 (名字,ip,now,ttl)、数命中几次,lookups 是真正向外发出去的解析次数(= 未命中次数)。
def query(cache, name, ip, now, ttl):
# 查一次:命中且没过期就用缓存并回 "hit";否则记进缓存(回填)并回 "miss"
if name in cache:
got_ip, born, got_ttl = cache[name]
if now - born < got_ttl:
return "hit"
cache[name] = (ip, now, ttl)
return "miss"
def hits(events):
# events: [(name, ip, now, ttl)],按顺序查,交回命中次数
cache = {}
n = 0
for name, ip, now, ttl in events:
if query(cache, name, ip, now, ttl) == "hit":
n += 1
return n
def expired(born, ttl, now):
# 记录是否已过期(活过了 ttl 秒就过期)
return now - born >= ttl
def lookups(events):
# 一串带缓存的查询里,真正向外发出去的解析次数(= 未命中次数)
return len(events) - hits(events)
c = {}
query(c, "a.com", "1.1.1.1", 0, 60)
print(query(c, "a.com", "1.1.1.1", 70, 60))
全部评论