一串查询命中几次

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

下面一串查询里(同名 TTL 60,时刻见代码),命中几次?

贯穿本节的 TTL 缓存:query(cache, 名字, ip, now, ttl) 查一次——缓存里有且没过期(now-存入时刻 < ttl)就交回 hit,否则把它记进缓存(回填)并交回 misshits(事件表) 按顺序查一串 (名字,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 = [("a.com","1.1.1.1",0,60), ("a.com","1.1.1.1",20,60), ("a.com","1.1.1.1",50,60), ("a.com","1.1.1.1",130,60)]
print(hits(evs))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论