|
1 | | -#include "LFUCache.h" |
2 | | -#include <iostream> |
| 1 | +#include "LRUCache.h" |
| 2 | +#include <algorithm> |
3 | 3 |
|
4 | | -LFUCache::LFUCache(int capacity) : capacity(capacity) {} |
| 4 | +LRUCache::LRUCache(size_t capacity) : capacity(capacity), hits(0), accesses(0) {} |
5 | 5 |
|
6 | | -int LFUCache::get(int key) { |
| 6 | +// --- New Methods --- |
| 7 | +double LRUCache::getHitRate() const { |
| 8 | + if (accesses == 0) return 0.0; |
| 9 | + return static_cast<double>(hits.load()) / accesses.load(); |
| 10 | +} |
| 11 | + |
| 12 | +void LRUCache::resetStats() { |
| 13 | + hits = 0; |
| 14 | + accesses = 0; |
| 15 | +} |
| 16 | +// --- |
| 17 | + |
| 18 | +int LRUCache::get(int key) { |
7 | 19 | std::lock_guard<std::mutex> lock(cache_mutex); |
8 | | - if (cache.find(key) == cache.end()) return -1; |
| 20 | + accesses++; // Track every access |
9 | 21 |
|
10 | | - touch(key); |
| 22 | + if (cache.find(key) == cache.end()) { |
| 23 | + return -1; // Miss |
| 24 | + } |
| 25 | + |
| 26 | + hits++; // Track hit |
| 27 | + moveToFront(key); |
11 | 28 | return cache[key].first; |
12 | 29 | } |
13 | 30 |
|
14 | | -void LFUCache::put(int key, int value) { |
| 31 | +void LRUCache::put(int key, int value) { |
15 | 32 | std::lock_guard<std::mutex> lock(cache_mutex); |
16 | | - |
17 | 33 | if (capacity == 0) return; |
18 | 34 |
|
19 | 35 | if (cache.find(key) != cache.end()) { |
20 | 36 | cache[key].first = value; |
21 | | - touch(key); |
| 37 | + moveToFront(key); |
22 | 38 | } else { |
23 | 39 | if (cache.size() >= capacity) { |
24 | 40 | evict(); |
25 | 41 | } |
26 | | - cache[key] = {value, 1}; |
27 | | - freq_map[1].push_front(key); |
| 42 | + cache[key] = {value, 0}; |
| 43 | + access_order.push_front(key); |
28 | 44 | } |
29 | 45 | } |
30 | 46 |
|
31 | | -void LFUCache::touch(int key) { |
32 | | - int old_freq = cache[key].second; |
33 | | - cache[key].second++; |
34 | | - freq_map[old_freq].remove(key); |
35 | | - freq_map[cache[key].second].push_front(key); |
| 47 | +// Unchanged private helpers... |
| 48 | +void LRUCache::moveToFront(int key) { |
| 49 | + access_order.remove(key); |
| 50 | + access_order.push_front(key); |
36 | 51 | } |
37 | 52 |
|
38 | | -void LFUCache::evict() { |
39 | | - for (auto& item : freq_map) { |
40 | | - if (!item.second.empty()) { |
41 | | - int key_to_evict = item.second.back(); |
42 | | - item.second.pop_back(); |
43 | | - cache.erase(key_to_evict); |
44 | | - break; |
45 | | - } |
46 | | - } |
| 53 | +void LRUCache::evict() { |
| 54 | + if (access_order.empty()) return; |
| 55 | + int key_to_evict = access_order.back(); |
| 56 | + access_order.pop_back(); |
| 57 | + cache.erase(key_to_evict); |
47 | 58 | } |
0 commit comments