这轮请求发几次解析
访问同一域名的一串请求(同名 TTL 100,时刻见代码),真正向外发出去的解析有几次?
贯穿本节的 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)
evs = [("api.x.com","1.2.3.4",0,100), ("api.x.com","1.2.3.4",10,100), ("api.x.com","1.2.3.4",20,100)]
print(lookups(evs))
全部评论