跳至主要內容
產品桌面工具TASTECAD圖面檢視TASTEFILES檔案管理TASTEFTP檔案傳輸TASTESSH遠端工作空間TASTEZIP壓縮與解壓縮TASTEWINM檔案管理開發工具TASTECODERust 整合開發環境TASTESTUDIO整合開發與測試環境TASTEETL資料整合(ETL)伺服器TASTEREMOTE遠端桌面伺服器TASTEGEO空間資訊伺服器TASTEMAIL郵件工作空間投資TASTESTOCK股票自動交易桌面應用程式開始使用下載文件購買所有產品
市集
資訊
技術資訊今日開發資訊開發文件程式語言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular伺服器框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express應用程式與桌面框架TauriFlutterReact NativeElectron演算法演算法基礎核心演算法進階演算法實務演算法
社群專案開發日誌提示詞AI 工具問題作品展示社群指南
合作技術傳授網站建置桌面應用程式建置發布與付款流程銷售合作夥伴聯絡我們
服務遠端桌面安裝包客製
TASTEDEV
產品

桌面工具

TASTECAD再複雜的圖面,也能輕鬆開啟TASTEFILES只挑需要的檔案,最快送達TASTEFTP讓檔案往來,走最俐落的路TASTESSH在你與伺服器之間,築起更穩固的連線TASTEZIP壓得更快,解得更安心TASTEWINM以鍵盤為主、用兩個窗格整理檔案的檔案管理器

開發工具

TASTECODE在一個視窗中完成 Rust 應用程式的編輯、建置、偵錯與測試TASTESTUDIO從編輯到遠端測試,再到經核准的 AI 修正TASTEETL邊看數值,邊搬資料

伺服器

TASTEREMOTE在自己的伺服器上運行的遠端桌面TASTEGEO以 Rust 重新打造相容 GeoServer 的空間資訊伺服器TASTEMAIL把郵件的主導權拿回自己手上

投資

TASTESTOCK何時、做什麼——依你訂下的規則運作的股票自動交易

開始使用

下載所有產品的最新版本文件各產品使用方法購買訂閱與永久授權所有產品一覽全部產品
所有產品
市集資訊
技術

資訊

今日開發資訊語言、框架、GitHub 與 AI 官方發布開發文件語言、框架與演算法指南

程式語言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
伺服器框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
應用程式與桌面框架TauriFlutterReact NativeElectron

演算法

演算法基礎複雜度分析 · 排序 · 搜尋 · 基礎資料結構 · 樹與堆積核心演算法圖形走訪 · 最短路徑與最小生成樹 · 動態規劃 · 貪婪演算法 · 分治法 · 回溯法進階演算法字串演算法 · 數學與數論 · 位元運算 · 線段樹 · 併查集實務演算法程式面試解題策略 · LRU 快取 · 速率限制 · 一致性雜湊
查看全部開發文件
社群
專案探索開發者與作品開發日誌決策與試錯提示詞可重複使用的指令AI 工具問題Claude、Codex、Gemini 的問題與替代做法作品展示已完成的成果社群指南我們如何公開打造
合作
技術傳授用 Rust 與 egui 打造原生應用程式網站建置10 種語言、帳號、文件與下載桌面應用程式建置Rust 與 egui,不用 WebView發布與付款流程簽章、MSI、deb、rpm、AppImage、雜湊銷售合作夥伴推薦即得 30%聯絡我們開發、合作與投資諮詢
服務
遠端桌面用瀏覽器連線你的電腦安裝包客製只裝需要的,設定預先放好
購買
繁
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登入
登入
TASTEDEV

從小工具到更好的開發。

support@tastedev.net支持 TASTEDEV
產品產品系列購買文件下載市集客戶支援
社群專案開發日誌提示詞AI 工具問題作品展示
政策關於我們隱私權政策服務條款訂閱條款退款政策社群規範
帳戶登入註冊
訪客
今天
昨天
累計瀏覽
公司名稱
GXSOFT
負責人
CHOI YOUNG GU
營業登記號碼
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
電子郵件
whitecalvin@tastedev.net
個人資料保護負責人
CHOI YOUNG GU

© 2026 TASTEDEV產品資訊以經驗證的開發原始碼為準。已發布·持續改進

LRU 快取 文件
LRU 快取
LRU Cache ConceptsHow an LRU Cache WorksImplementing an LRU CacheComplexity of an LRU CacheLRU Practice ProblemsLRU in the Real World
討論

LRU 快取 指南 · 5/6

LRU Practice Problems

本章目前僅提供英文版。

These four problems extend the basic LRU cache in directions that come up in interviews and in real code. Try each one before reading the approach. The solutions use OrderedDict to keep the focus on the idea; you can swap in the hand-written linked list from the implementation chapter.

Problem 1: Count the misses

A program issues a sequence of page requests, and memory holds k pages managed by LRU. Return the number of misses (page faults). Then find the smallest k for which the number of misses is at most a given limit.

Approach: simulate the cache once per capacity. Because LRU is a stack algorithm, misses never increase when k grows, so the smallest suitable k can be found with binary search over 1..number of distinct pages.

from collections import OrderedDict

def lru_misses(requests, k):
    cache, misses = OrderedDict(), 0
    for page in requests:
        if page in cache:
            cache.move_to_end(page)
        else:
            misses += 1
            cache[page] = True
            if len(cache) > k:
                cache.popitem(last=False)
    return misses

def smallest_capacity(requests, limit):
    lo, hi = 1, max(1, len(set(requests)))
    while lo < hi:
        mid = (lo + hi) // 2
        if lru_misses(requests, mid) <= limit:
            hi = mid
        else:
            lo = mid + 1
    return lo

reqs = [1, 2, 3, 1, 4, 1, 2, 5, 1, 2, 3, 4]
print(lru_misses(reqs, 3))         # 8
print(smallest_capacity(reqs, 7))  # 4

Problem 2: LRU with expiry

Extend the cache so that every entry also expires ttl seconds after it was written. An expired entry behaves like a missing one. The clock must be injectable so the cache can be tested without sleeping.

Approach: store (value, expires_at). Check the expiry on get and delete stale entries lazily. Capacity eviction still follows LRU order. Lazy expiry keeps both operations O(1); expired entries may occupy space until they are read or evicted, which is the same trade-off Redis makes alongside its active expiry cycle.

import time
from collections import OrderedDict

class TTLLRUCache:
    def __init__(self, capacity, ttl, clock=time.monotonic):
        self.capacity, self.ttl, self.clock = capacity, ttl, clock
        self.data = OrderedDict()            # key -> (value, expires_at)

    def get(self, key, default=None):
        item = self.data.get(key)
        if item is None:
            return default
        value, expires_at = item
        if self.clock() >= expires_at:
            del self.data[key]               # lazy expiry
            return default
        self.data.move_to_end(key)
        return value

    def put(self, key, value):
        self.data[key] = (value, self.clock() + self.ttl)
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)

now = [0.0]
c = TTLLRUCache(2, ttl=10, clock=lambda: now[0])
c.put("a", 1)
now[0] = 5;  print(c.get("a"))   # 1
now[0] = 11; print(c.get("a"))   # None (expired)
對本章有疑問嗎?
上一章Complexity of an LRU Cache下一章LRU in the Real World

Problem 3: Byte-limited cache

Entries have different sizes. The cache has a byte budget instead of an entry count. Inserting a value must evict least recently used entries until the new value fits. A value larger than the whole budget is not cached at all.

Approach: keep a running total of bytes. After an insert or update, pop from the least recent end while the total exceeds the budget. Each entry is evicted at most once after being inserted, so the cost is O(1) amortized per operation.

from collections import OrderedDict

class ByteLRU:
    def __init__(self, max_bytes):
        self.max_bytes, self.used = max_bytes, 0
        self.data = OrderedDict()            # key -> bytes

    def get(self, key):
        if key not in self.data:
            return None
        self.data.move_to_end(key)
        return self.data[key]

    def put(self, key, blob):
        if len(blob) > self.max_bytes:
            return False
        if key in self.data:
            self.used -= len(self.data.pop(key))
        self.data[key] = blob
        self.used += len(blob)
        while self.used > self.max_bytes:
            _, old = self.data.popitem(last=False)
            self.used -= len(old)
        return True

b = ByteLRU(10)
b.put("x", b"12345"); b.put("y", b"1234"); b.get("x")
b.put("z", b"123")              # 12 bytes: evicts "y"
print(list(b.data), b.used)     # ['x', 'z'] 8

Problem 4: Memoize with a recency limit

A recursive function counts paths in a grid where some cells are blocked. Memoize it with a bounded LRU cache and report the hit ratio. Then explain why maxsize that is too small slows the function down.

Approach: decorate the function with functools.lru_cache(maxsize=...) and read cache_info(). Recursion revisits recent subproblems, so even a modest cache helps, but when maxsize is smaller than the active frontier the cache thrashes and most calls miss.

from functools import lru_cache

BLOCKED = {(1, 1), (2, 3)}
ROWS, COLS = 6, 6

@lru_cache(maxsize=64)
def paths(r, c):
    if (r, c) in BLOCKED or r >= ROWS or c >= COLS:
        return 0
    if (r, c) == (ROWS - 1, COLS - 1):
        return 1
    return paths(r + 1, c) + paths(r, c + 1)

print(paths(0, 0))
info = paths.cache_info()
print(f"hit ratio {info.hits / (info.hits + info.misses):.2f}")

Summary

  • Simulation plus the stack property of LRU turns capacity planning into a binary search.
  • TTL, byte budgets and memoization are all small extensions of the same ordered map.
  • Always reason about what happens when an update, an oversized value or a tiny capacity arrives.

0 則留言

熱門留言由新到舊

登入 · 登入後即可留言。