Spaces:
Sleeping
Sleeping
Create adaptive_cache/simulator.py
Browse files- adaptive_cache/simulator.py +27 -0
adaptive_cache/simulator.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
class CacheSimulator:
|
| 4 |
+
def __init__(self, capacity: int):
|
| 5 |
+
self.capacity = capacity
|
| 6 |
+
# -1 represents an empty cache slot
|
| 7 |
+
self.cache = np.full(capacity, -1, dtype=np.int32)
|
| 8 |
+
self.last_access_time = np.zeros(capacity, dtype=np.int32)
|
| 9 |
+
self.current_time = 0
|
| 10 |
+
|
| 11 |
+
def request_item(self, item_id: int) -> bool:
|
| 12 |
+
"""Returns True if hit, False if miss. Does not evict."""
|
| 13 |
+
self.current_time += 1
|
| 14 |
+
|
| 15 |
+
hit_indices = np.where(self.cache == item_id)[0]
|
| 16 |
+
if len(hit_indices) > 0:
|
| 17 |
+
idx = hit_indices[0]
|
| 18 |
+
self.last_access_time[idx] = self.current_time
|
| 19 |
+
return True
|
| 20 |
+
|
| 21 |
+
return False
|
| 22 |
+
|
| 23 |
+
def evict_and_insert(self, slot_index: int, item_id: int):
|
| 24 |
+
"""Places the new item in the specified cache slot."""
|
| 25 |
+
if 0 <= slot_index < self.capacity:
|
| 26 |
+
self.cache[slot_index] = item_id
|
| 27 |
+
self.last_access_time[slot_index] = self.current_time
|