LRU是什么
LRU是一种缓存淘汰算法(在OS中也叫内存换页算法),LRU是Least recently used的缩写,即“最近最少使用”,由于缓存资源有限,所以要淘汰缓存中不常用的数据,留下常用的数据,达到缓存效率的最大化。LRU就是这样一种决定“淘汰谁留下谁”的算法。
算法规则
添加数据:
- 有新数据(意味着数据之前没有被缓存过)添加时,加入到列表头部
- 缓存到达最大容量时,需要淘汰数据多出来的数据,此时淘汰列表尾部的数据
- 当缓存中有数据被命中,则将数据移动到列表头部(相当于新加入缓存)
取数据(访问数据):
- 如果没有该数据,返回-1
- 如果有该数据,取出该数据,并放在列表头部,并返回该数据
在Python的collections包中,已经内置了这种实用的结构OrderedDict,OrderedDict是字典(dict)的子类,既有元素排序的特点,又有hash的数据结构,快速判断数据是否存在,解决列表实现的性能问题。
import collections class LRUCache: def __init__(self, capacity): self.capacity = capacity self.queue = collections.OrderedDict() def get(self, key): if key not in self.queue: return -1 value = self.queue.pop(key) self.queue[key] = value return self.queue[key] def put(self, key, value): if key in self.queue: self.queue.pop(key) elif len(self.queue.items()) == self.capacity: self.queue.popitem(last=False) self.queue[key] = value c = LRUCache(5) for i in range(5,10): c.put(i,10*i) x = c.get(6) print(c.queue)