-
Notifications
You must be signed in to change notification settings - Fork 11
/
lrutest.py
67 lines (55 loc) · 1.42 KB
/
lrutest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
# Author Dario Clavijo 2018
# GPLv2
class LRU:
def __init__(self, limit):
self.col = {}
self.access = {}
self.limit = limit
def insert(self, key, value):
self.col[key] = value
# self.access[key] = 2
self.access[key] = 1
def purge(self):
pops = []
t = {}
for k in self.access:
# if self.access[k] > 0:
try:
t[self.access[k]] += [k]
except:
t[self.access[k]] = [k]
nokeep = sorted(t)
nokeep = nokeep[: len(nokeep) - self.limit]
print(nokeep)
for n in nokeep:
for k in t[n]:
self.access.pop(k)
self.col.pop(k)
def get(self, key):
try:
# self.access[key] = (self.access[key] >> 2) + 1
self.access[key] += 1
return self.col[key]
except:
return None
def test():
lru = LRU(4)
for i in range(0, 21):
lru.insert(f"key{str(i)}", str(i))
for _ in range(0, 1000):
lru.get("key13")
for _ in range(0, 500):
lru.get("key11")
for _ in range(0, 250):
lru.get("key7")
for _ in range(0, 125):
lru.get("key5")
lru.get("key3")
lru.get("key2")
lru.get("key1")
print(lru.access)
for _ in range(0, 3):
lru.purge()
print(lru.access)
test()