Last active
February 17, 2023 02:39
-
-
Save Gerardwx/c60d200b4db8e7864cb3342dd19d41c9 to your computer and use it in GitHub Desktop.
Least recently used dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import collections | |
import random | |
from typing import Hashable, Any, Optional, Dict, Tuple | |
class LruCache: | |
"""Dictionary like storage of most recently inserted values""" | |
def __init__(self, size: int = 1000): | |
""":param size number of cached entries""" | |
assert isinstance(size, int) | |
self.size = size | |
self.insert_counter = 0 | |
self.oldest = 0 | |
self._data : Dict[Hashable,Tuple[Any,int]]= {} # store values and age index | |
self._lru: Dict[int, Hashable] = {} # age counter dictionary | |
def insert(self, key: Hashable, value: Any) -> None: | |
"""Insert into dictionary""" | |
existing = self._data.get(key, None) | |
self._data[key] = (value, self.insert_counter) | |
self._lru[self.insert_counter] = key | |
if existing is not None: | |
self._lru.pop(existing[1], None) # remove old counter value, if it exists | |
self.insert_counter += 1 | |
if (sz := len(self._data)) > self.size: # is cache full? | |
assert sz == self.size + 1 | |
while ( | |
key := self._lru.get(self.oldest, None)) is None: # index may not be present, if value was reinserted | |
self.oldest += 1 | |
del self._data[key] # remove oldest key / value from dictionary | |
del self._lru[self.oldest] | |
self.oldest += 1 # next oldest index | |
assert len(self._lru) == len(self._data) | |
def get(self, key: Hashable) -> Optional[Any]: | |
"""Get value or return None if not in cache""" | |
if (tpl := self._data.get(key, None)) is not None: | |
return tpl[0] | |
return None | |
if __name__ == "__main__": | |
CACHE_SIZE = 1000 | |
TEST_SIZE = 1_000_000 | |
cache = LruCache(size=CACHE_SIZE) | |
all = [] | |
for i in range(TEST_SIZE): | |
all.append(random.randint(-5000, 5000)) | |
summary = collections.defaultdict(int) | |
for value in all: | |
cache.insert(value, value * value) | |
summary[value] += 1 | |
smallest = TEST_SIZE | |
largest = -TEST_SIZE | |
total = 0 | |
for value, count in summary.items(): | |
smallest = min(smallest, count) | |
largest = max(largest, count) | |
total += count | |
avg = total / len(summary) | |
print(f"{len(summary)} values occurrences range from {smallest} to {largest}, average {avg:.1f}") | |
recent = set() # recent most recent entries | |
for i in range(len(all) - 1, -1, -1): # loop backwards to get the most recent entries | |
value = all[i] | |
if len(recent) < CACHE_SIZE: | |
recent.add(value) | |
if value in recent: | |
if (r := cache.get(value)) != value * value: | |
raise ValueError(f"Cache missing recent {value} {r}") | |
else: | |
if cache.get(value) != None: | |
raise ValueError(f"Cache includes old {value}") | |
Copyright 2022 Gerard Weatherby | |
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment