Skip to content

Commit 37c24ef

Browse files
authored
Update LRUCache.cpp
1 parent 284a7dc commit 37c24ef

File tree

1 file changed

+36
-25
lines changed

1 file changed

+36
-25
lines changed

src/LRUCache.cpp

Lines changed: 36 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,58 @@
1-
#include "LFUCache.h"
2-
#include <iostream>
1+
#include "LRUCache.h"
2+
#include <algorithm>
33

4-
LFUCache::LFUCache(int capacity) : capacity(capacity) {}
4+
LRUCache::LRUCache(size_t capacity) : capacity(capacity), hits(0), accesses(0) {}
55

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) {
719
std::lock_guard<std::mutex> lock(cache_mutex);
8-
if (cache.find(key) == cache.end()) return -1;
20+
accesses++; // Track every access
921

10-
touch(key);
22+
if (cache.find(key) == cache.end()) {
23+
return -1; // Miss
24+
}
25+
26+
hits++; // Track hit
27+
moveToFront(key);
1128
return cache[key].first;
1229
}
1330

14-
void LFUCache::put(int key, int value) {
31+
void LRUCache::put(int key, int value) {
1532
std::lock_guard<std::mutex> lock(cache_mutex);
16-
1733
if (capacity == 0) return;
1834

1935
if (cache.find(key) != cache.end()) {
2036
cache[key].first = value;
21-
touch(key);
37+
moveToFront(key);
2238
} else {
2339
if (cache.size() >= capacity) {
2440
evict();
2541
}
26-
cache[key] = {value, 1};
27-
freq_map[1].push_front(key);
42+
cache[key] = {value, 0};
43+
access_order.push_front(key);
2844
}
2945
}
3046

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);
3651
}
3752

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);
4758
}

0 commit comments

Comments
 (0)