-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate-test.py
186 lines (141 loc) · 4.8 KB
/
rate-test.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import redis
import random
from collections import OrderedDict, Counter, deque
import numpy as np
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# Simulate data for 1000 movies
keys = [f"movie_{i}" for i in range(1, 1001)] # 1000 movies
values = [f"info_{i}" for i in range(1, 1001)]
test_data = dict(zip(keys, values))
# Load test data into Redis
for key, value in test_data.items():
r.set(key, value)
# Generate 10000 random access requests
requests = random.choices(keys, k=10000)
# Cache Strategy Classes
class LRUCache:
""" Least Recently Used (LRU) cache strategy """
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key in self.cache:
self.cache.move_to_end(key)
return True
return False
def put(self, key):
self.cache[key] = None
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
class LFUCache:
""" Least Frequently Used (LFU) cache strategy """
def __init__(self, capacity):
self.capacity = capacity
self.cache = {} # Store key-value pairs
self.freq = Counter() # Track access frequency
def get(self, key):
if key in self.cache:
self.freq[key] += 1
return True
return False
def put(self, key):
if len(self.cache) >= self.capacity:
# Find and evict the least frequently used key
lfu_key = self.freq.most_common()[:-2:-1][0][0]
self.cache.pop(lfu_key)
self.freq.pop(lfu_key)
self.cache[key] = None
self.freq[key] = 1
class RandomCache:
""" Random replacement cache strategy """
def __init__(self, capacity):
self.capacity = capacity
self.cache = set()
def get(self, key):
return key in self.cache
def put(self, key):
if len(self.cache) >= self.capacity:
self.cache.remove(random.choice(list(self.cache)))
self.cache.add(key)
class FIFOCache:
""" First-In-First-Out cache strategy """
def __init__(self, capacity):
self.capacity = capacity
self.cache = set()
self.order = deque()
def get(self, key):
return key in self.cache
def put(self, key):
if len(self.cache) >= self.capacity:
oldest = self.order.popleft()
self.cache.remove(oldest)
self.cache.add(key)
self.order.append(key)
class MRUCache:
""" Most Recently Used cache strategy """
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
def get(self, key):
if key in self.cache:
return True
return False
def put(self, key):
self.cache[key] = None
if len(self.cache) > self.capacity:
# Delete the most recently used element
last = next(reversed(self.cache))
del self.cache[last]
class SHiPCache:
""" SHiP (Signature History based Predictor) cache strategy """
def __init__(self, capacity):
self.capacity = capacity
self.main_cache = set()
self.history = set()
def get(self, key):
if key in self.main_cache:
return True
if key in self.history:
self.history.remove(key)
self.main_cache.add(key)
return True
return False
def put(self, key):
if len(self.main_cache) + len(self.history) >= self.capacity:
if len(self.history) > 0:
self.history.pop()
else:
self.main_cache.pop()
self.history.add(key)
# Define a function to test different cache replacement strategies
def test_cache_strategy(cache_class, capacity, requests):
cache = cache_class(capacity)
hits, misses = 0, 0
for req in requests:
if cache.get(req):
hits += 1
else:
misses += 1
cache.put(req)
return hits / len(requests)
# Test Cache Strategies
# Test FIFO Strategy
fifo_hit_rate = test_cache_strategy(FIFOCache, 100, requests)
print(f"FIFO Hit rate: {fifo_hit_rate:.4f}")
# Test Random Strategy
random_hit_rate = test_cache_strategy(RandomCache, 100, requests)
print(f"Random Hit rate: {random_hit_rate:.4f}")
# Test LFU Strategy
lfu_hit_rate = test_cache_strategy(LFUCache, 100, requests)
print(f"LFU Hit rate: {lfu_hit_rate:.4f}")
# Test LRU Strategy
lru_hit_rate = test_cache_strategy(LRUCache, 100, requests)
print(f"LRU Hit rate: {lru_hit_rate:.4f}")
# Test MRU Strategy
mru_hit_rate = test_cache_strategy(MRUCache, 100, requests)
print(f"MRU Hit rate: {mru_hit_rate:.4f}")
# Test SHiP Strategy
ship_hit_rate = test_cache_strategy(SHiPCache, 100, requests)
print(f"SHiP Hit rate: {ship_hit_rate:.4f}")