CPU Socket中Cache的理解
LRU Cache 最近最少使用的缓存放在淘汰的位置
两个要点: 大小,替换策略
实现: Hash Table + Double LinkedList
复杂度: O(1)查询, O(1)修改,更新
LRU cache工作示例
替换策略:
LFU - least frequently used 统计每个元素使用到的频次最少
LRU - least recently used
替换算法
LRU Cache
面试题 16.25. LRU缓存
146. LRU缓存机制
# Python
class LRUCache(object):
def __init__(self, capacity):
self.dic = collections.OrderedDict() # OrderedDict的get和put比较简单
self.remain = capacity # remain得到capacity
def get(self, key):
if key not in self.dic:
return -1
v = self.dic.pop(key)
self.dic[key] = v # key as the newest one
return v
def put(self, key, value):
if key in self.dic: # 如果key已经在字典中,只要pop出去即可
self.dic.pop(key)
else:
if self.remain > 0: #不然就判断remain到底够不够,remain还够的话,就-1
self.remain -= 1
else: # self.dic is full #remain = 0不够,就要弹一个最老的元素,空一个位置
self.dic.popitem(last=False)
self.dic[key] = value
python知识点:class collections.OrderedDict([items])
继承自dict, 与dict不同的是, dict由于hash的特性,是无序的, 而OrderedDict是有序的, 是依照插入的顺序排列的。
- popitem(last=True)
该方法返回并删除一个(key, value)对, 删除的顺序遵循:
如果参数设置为True, 则为:LIFO, 后进先出。
如果参数设置为False, 则为:FIFO, 先进先出。- move_to_end(key, last=True)
将现有 key 移动到有序字典的任一端。
如果 last 为真值(默认)则将元素移至末尾;
如果 last 为假值则将元素移至开头。
如果 key 不存在则会触发 KeyError:
//C/C++
struct CacheNode {
int key, value;
CacheNode *pre, *next;
CacheNode(int key_ = 0, int value_ = 0)
: key(key_), value(value_), pre(NULL), next(NULL) {
}
};
class LRUCache {
public:
LRUCache(int capacity)
: _capacity(capacity), _head(new CacheNode()), _tail(_head) {
}
int get(int key) {
auto it = _cache.find