最不經常使用 (LFU) 實現
記憶體快取是軟體或硬體的一個組成部分,它將頻繁訪問的資料儲存在一個方便的位置。快取用於透過減少訪問資料所需的能量來提高系統性能。記憶體容量決定了快取可以儲存多少資料。當記憶體快取已滿時,必須逐出一些資料以騰出空間用於新資料。
接下來,是世界末日的事實。最不經常使用 (LFU) 快取儲存替換策略就是這些策略之一。LFU 快取中的所有內容都有一個使用計數,指示該專案被訪問的次數。當記憶體快取已滿時,因此,將刪除使用次數最少的專案。這種方法基於以下前提:使用頻率低的專案在未來使用頻率會更低。
可以使用允許快速查詢、插入和刪除專案的資料結構來實現 LFU 快取。字典(或雜湊表)是執行此任務的絕佳選擇。以下是使用Python 中的字典實現 LFU 快取的方法:
Python
class LFUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} # Dictionary to store the items in the cache self.counts = {} # Dictionary to store the usage count of each item def get(self, key: int) -> int: if key in self.cache: # Increment the usage count of the item self.counts[key] += 1 return self.cache[key] else: return -1 def put(self, key: int, value: int) -> None: if self.capacity == 0: return if key in self.cache: # Update the value of the item and increment its usage count self.cache[key] = value self.counts[key] += 1 else: if len(self.cache) >= self.capacity: # Evict the item with the lowest usage count min_count = min(self.counts.values()) items = [k for k, v in self.counts.items() if v == min_count] del self.cache[items[0]] del self.counts[items[0]] # Add the new item to the cache with a usage count of 1 self.cache[key] = value self.counts[key] = 1 cache = LFUCache(2) # Create an LFU cache with capacity 2 cache.put(1, 1) # Add key 1 with value 1 to the cache cache.put(2, 2) # Add key 2 with value 2 to the cache print(cache.get(1)) # Output: 1 cache.put(3, 3) # Add key 3 with value 3 to the cache, evicting key 2 print(cache.get(2)) # Output: -1 (key 2 is no longer in the cache) print(cache.get(3)) # Output: 3 cache.put(4, 4) # Add key 4 with value 4 to the cache, evicting key 1 print(cache.get(1)) # Output: -1 (key 1 is no longer in the cache) print(cache.get(3)) # Output: 3 print(cache.get(4)) # Output: 4
輸出
1 -1 3 -1 3 4
init 命令
'__init__' 方法建立兩個字典:'self.cache' 用於保留快取中的專案,以及 'self.counts' 用於保留每個專案的利用計數。
get 命令
'get' 方法在快取中搜索指定的鍵,如果找到,則遞增專案的利用計數並返回其值。如果找不到該鍵,則該函式返回'-1'。
put 命令
'put' 方法在快取中新增或修改鍵值對。如果該鍵已存在於快取中,則更新專案的 value 並遞增其使用計數。如果該鍵尚不存在於快取中,則新增鍵值對,如果記憶體快取已滿,則會逐出使用計數最低的專案及其值。'min' 操作用於確定'self.counts' 中使用計數最低的專案,然後使用所得資訊查詢'self.cache' 中所有具有該使用計數的專案。然後刪除該專案列表中的第一個專案。
此實現提供了一種有效的實現方法。最後,LFU 快取使用基於頻寬的逐出規則來確定儲存空間已滿時要刪除哪些專案。當專案快取已滿且需要新專案時,將逐出使用計數最少的專案。這確保快取始終包含最常使用的專案,這可以帶來更高的快取命中率和效能。
LFU 快取實現使用雜湊表和優先順序佇列資料結構來有效地維護快取及其使用計數。
結論
LFU 快取是一種快取技術,當快取記憶體已滿時,它會從快取中刪除最不經常使用的專案。它在資源有限且必須最佳化資源實現的情況下很有用。
LFU 快取應用程式是在需要快取時處理有限資源的有效方法。它可以用於各種目的,包括網頁快取資訊、資料庫快取和目錄快取。但是,維護使用計數和管理快取逐出策略需要大量的計算開銷。此外,任務的特性和資料訪問模式會影響其效能。