Compare commits

...

9 Commits

Author SHA1 Message Date
CIber_prayer 1916781bbb variation of tests 2024-09-23 14:58:08 +03:00
CIber_prayer 539df093a3 final comit 2024-09-22 15:54:31 +03:00
CIber_prayer 49ef72e1ea final comit 2024-09-22 15:51:02 +03:00
CIber_prayer 49410552c6 dont work on windows
i dont know why
2024-09-22 15:23:43 +03:00
CIber_prayer 1a84f77192 ideal_cache 2024-09-22 03:26:07 +03:00
CIber_prayer 552953591e ideal_cache 2024-09-22 03:25:10 +03:00
CIber_prayer 55345b7c76 ideal_cache_1_ver 2024-09-21 16:19:03 +03:00
CIber_prayer a21fc9e08d bugs fixed 2024-09-21 11:53:10 +03:00
CIber_prayer 1860adceff bugs fixed 2024-09-21 11:51:04 +03:00
9 changed files with 155 additions and 60 deletions
+4 -1
View File
@@ -1,3 +1,6 @@
*.o
*
*.
*.txt
*.vscode
*.out
*.exe
+32 -22
View File
@@ -18,68 +18,78 @@ private:
std::list <int> q2; //slow queue - if page asked at the first time put it to q2, if itasked from q2 it put it to q1,
public:
int tic_number = 0;
TwoCache(size_t q1sz, size_t q2sz): cpct_q1(q1sz), cpct_q2(q2sz) {} //ctor
void put_page(int id) {
std::cout << "id: " << id << std::endl;
//std::cout <<__LINE__ << " " << __FILE__<< std::endl;
//std::cout << "id: " << id << std::endl;
if (umap1.find(id) != umap1.end()) { //page is found, nothing to do (fast case)
std::cout << "id ="<<id<<" TIC!\n";
//std::cout << "id ="<<id<<" TIC!\n";
print_info();
tic_number++;
//print_info();
return;
} else if (umap2.find(id) != umap2.end()) {
std::cout << "id ="<<id<<" TIC!\n";
//std::cout << "id ="<<id<<" TIC!\n";
print_info();
tic_number++;
q2.erase(umap2[id]);
//if page is in slow put it in fast
std::cout <<__LINE__ << " " << __FILE__<< std::endl;
umap2.erase(id);
if (q1.size() < cpct_q1) {
print_info();
//print_info();
q1.push_front(id);
umap1[id] = q1.begin();
//print_info();
} else {
print_info();
//print_info();
int lru_page = q1.back(); //if fast is overflow - delete
auto lru_page = q1.back(); //if fast is overflow - delete
umap1.erase(lru_page);
q1.pop_back();
auto p = umap1.find(lru_page);
umap1.erase(p);
// std::cout << "ERASING " << lru_page << "\n";
// umap1.erase(lru_page);
// std::cout << "KAAAAl"`<<*(umap1[lru_page]) << "\n";
q1.push_front(id);
umap1[id] = q1.begin();
//print_info();
return;
}
} else if (q2.size() < cpct_q2) { //if not in cache put it in slow
print_info();
//print_info();
q2.push_front(id);
umap2[id] = q2.begin();
//print_info();
return;
} else { //if slow is overflow - pop
print_info();
//print_info();
int lru_page = q2.back(); //if fast is overflow - delete
umap2.erase(lru_page);
q2.pop_back();
auto p = umap2.find(lru_page);
std::cout<< "ERASING " << *(umap2[lru_page]) <<std::endl;
umap2.erase(p);
q2.push_front(id);
umap2[id] = q2.begin();
return;
//print_info();
}
}
+69
View File
@@ -0,0 +1,69 @@
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
class Ideal_Cache {
private:
int capacity;
std::vector<int> cache;
std::unordered_map<int, int> cacheMap; // Для быстрого доступа к индексам
public:
Ideal_Cache(size_t capacity) : capacity(capacity) {}
int tic_number = 0;
void get_request_vector(const std::vector<int>& requests) {
// смотрим есть ли айди в кэше
// Есть - тик
// Нет - смотрим размер, если размер не полный добавляем в кэш
// если размер полный, то уберем тот, который позже всех встретится
for (size_t i = 0; i < requests.size(); ++i) {
int item = requests[i];
if (cacheMap.find(item) != cacheMap.end()) {
tic_number++; //tic
continue;
}
if (cache.size() < capacity) {
cache.push_back(item);
cacheMap[item] = cache.size() - 1;
} else {
int farthest = -1;
int indexToRemove = -1;
for (size_t j = 0; j < cache.size(); ++j) {
auto nextIndex = std::find(requests.begin() + i, requests.end(), cache[j]); //находим следующее вхождение (начиная с i ого тк предыдущие обработались)
if (nextIndex == requests.end()) {
indexToRemove = j; //В конце удалим последний
break;
} else {
int nextIdx = std::distance(requests.begin(), nextIndex);
if (nextIdx > farthest) {
farthest = nextIdx;
indexToRemove = j;
}
}
}
cacheMap.erase(cache[indexToRemove]);
cache[indexToRemove] = item;
cacheMap[item] = indexToRemove;
}
}
}
void info() const {
std::cout << "ideal cache: ";
for (int item : cache) {
std::cout << item << " ";
}
std::cout << std::endl;
}
};
+11 -3
View File
@@ -1,14 +1,22 @@
# Алгоритм кэширования 2Q
Алгоритм кэширования 2Q (Two Queues) представляет собой метод управления кэш-памятью. Этот алгоритм состоит из двух очередей: q1 и q2. q1 является буфером, в который добавляются данные только в начале и замещаются из конца, а q2 используется для хранения "недавно использованных" данных.
# Тестирование
Генератор тестов - test_gen.py спрашивает количество тестов и создает pytests.txt
# Запуск тестов
make test - собирает программу затем
./cache_test "test_file_name"
## Напиример:
./cache_test pytests.txt
# Принцип работы
Когда данные добавляются в кэш, они помещаются в начало q1.
Если данные извлекаются из кэша, они перемещаются из q1 в начало q2.
Если данные снова запрашиваются и они находятся в q2, они перемещаются в конец q1.
Если данные снова запрашиваются и их уже нет в кэше, они добавляются в начало q1, а если q1 заполнена, то данные из конца q1 удаляются и добавляются новые данные в начало q1.
# Преимущества
## Эффективность: алгоритм 2Q обладает хорошей производительностью и способен эффективно управлять кэш-памятью.
## Адаптивность: алгоритм автоматически регулируется в зависимости от обращаемости данных, приспосабливаясь к изменениям в запросах.
## Эффективность:
алгоритм 2Q обладает хорошей производительностью и способен эффективно управлять кэш-памятью.
## Адаптивность:
алгоритм автоматически регулируется в зависимости от обращаемости данных, приспосабливаясь к изменениям в запросах.
## Недостатки
Не подходит для всех типов данных: алгоритм 2Q неэффективен для случаев, когда данные необходимо хранить в определённом порядке.
Сложность реализации: реализация алгоритма кэширования 2Q может быть более сложной, чем у других методов управления кэш-памятью.
Executable
BIN
View File
Binary file not shown.
+19 -6
View File
@@ -1,7 +1,10 @@
#include <iostream>
#include <fstream>
#include "2Q_cache.h"
#include "Ideal_cache.h"
#include <sstream>
#include <vector>
#include <algorithm>
const char* default_test_file = "tests.txt";
@@ -18,26 +21,35 @@ int cache_test(std::string file_name) {
std::string test_line, answer_line;
int fast_q_sz, slow_q_sz, num_of_calls, page_id, test_number = 0;
int fast_q_sz, slow_q_sz, num_of_calls, page_id, test_number = 0, test_passed = 0, test_failed = 0;
while(std::getline(file, test_line)) {
while (std::getline(file, test_line)) {
std::stringstream ss(test_line);
ss >> fast_q_sz >> slow_q_sz>>num_of_calls; //read input
TwoCache cache(fast_q_sz, slow_q_sz); //initialising
Ideal_Cache ideal_cache(fast_q_sz + slow_q_sz);
for(int i = 0; i < num_of_calls; i++) { //executing
std::vector <int> requests;
for (int i = 0; i < num_of_calls; i++) { //executing
ss >> page_id;
cache.put_page(page_id);
requests.push_back(page_id);
}
ideal_cache.get_request_vector(requests);
std::getline(file, answer_line);
if(cache.string_info() == answer_line) { //compare answers
if (cache.string_info() == answer_line) { //compare answers
std::cout << "test - " << test_number << " passed\n";
std::cout << "ideal tics/your tics " << ideal_cache.tic_number << "/" << cache.tic_number << std::endl;
test_passed++;
} else {
std::cout << "test - " << test_number << " failed\n";
std::cout << "right answer - " << answer_line << "your answer - " << cache.string_info() << std::endl;
test_failed++;
}
test_number++;
@@ -45,14 +57,15 @@ int cache_test(std::string file_name) {
file.close();
std::cout << "\nNumber of tests = "<< test_number << "\nTests passed = " << test_passed << "\nTests failed = " << test_failed << "\n";
return 0;
}
int main(int argc, char* argv[]) {
if(argc == 0) {
if (argc == 0) {
cache_test(default_test_file);
} else {
cache_test(argv[1]);
}
}
+14 -14
View File
@@ -1,33 +1,33 @@
TARGET = Q2
CXX = g++
CXXFLAGS = -Wall -Wextra -std=c++11
SRCS = main.cpp
TEST = cache_test.cpp
OBJS = $(SRCS:.cpp=.o)
ifeq ($(OS),Windows_NT)
RM = del
RUN = $(TARGET).exe
else
RM = rm -f
RUN = ./$(TARGET)
endif
OBJS = $(SRCS:.cpp=.o)
all: $(TARGET)
$(TARGET): $(OBJS)
$(CXX) -o $@ $^
$(CXX) -o $@ $^
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@
$(CXX) $(CPPFLAGS) -c $< -o $@
test:
$(CXX) $(CXXFLAGS) $(TEST) -o cache_test
$(CXX) $(CPPFLAGS) $(TEST) -o cache_test
clean:
$(RM) $(OBJS) $(TARGET) cache_test
rm -f $(OBJS) $(TARGET) cache_test
run: $(TARGET)
$(RUN)
./$(TARGET)
ifeq ($(OS), Windows_NT)
clean:
del /Q $(OBJS) $(TARGET) cache_test
run: $(TARGET)
$(TARGET).exe
endif
.PHONY: all clean run test
+1 -1
View File
@@ -45,7 +45,7 @@ if __name__ == "__main__":
vect = []
szq1 = random.randint(5, 10)
szq2 = random.randint(5, 10)
num_of_requests = (random.randint(1, 100))
num_of_requests = (random.randint(1, 1000000))
cache = Cache(szq1, szq2)
-8
View File
@@ -1,8 +0,0 @@
1 1 10 1 1 1 1 1 2 2 2 2 3
2 3
3 4 16 1 2 3 4 5 6 1 2 3 1 4 5 3 4 6 7
4 3 1 7 6 5 2
3 10 10 1 2 3 1 2 3 6 8 9 11
3 2 1 11 9 8 6
10 10 20 1 2 3 4 5 6 7 8 9 10 11 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 11