Skip to content

Commit

Permalink
Add program for analyting client logs
Browse files Browse the repository at this point in the history
  • Loading branch information
resetius committed Dec 4, 2023
1 parent 9b73624 commit c8a8a29
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions client/percentiles2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#include <iostream>
#include <queue>
#include <set>
#include <vector>

#include <stdint.h>
#include <stdio.h>

using namespace std;

class SlidingWindowPercentile {
public:
SlidingWindowPercentile(int windowSize)
: windowSize(windowSize) {}

void addNumber(uint64_t num) {
if (windowQueue.size() >= windowSize) {
// Удаляем самый старый элемент
auto oldest = windowQueue.front();
windowQueue.pop();
auto it = windowSorted.find(oldest);
if (it != windowSorted.end()) {
windowSorted.erase(it);
}
}

windowQueue.push(num);
windowSorted.insert(num);
}

uint64_t getPercentile(int targetPercentile) {
if (windowSorted.empty()) {
return -1; // Окно пусто
}

int index = (targetPercentile * windowSorted.size()) / 100;
auto it = windowSorted.begin();
std::advance(it, index);
return *it;
}

private:
std::queue<uint64_t> windowQueue; // Сохраняет элементы в порядке их добавления
std::multiset<uint64_t> windowSorted; // Отсортированные элементы окна
int windowSize;
};

int main() {
// Пример использования
SlidingWindowPercentile calculator(1000000); // 50-й перцентиль с размером окна 5
vector<int> p = {50, 80, 90, 99};
uint64_t num;

while (fscanf(stdin, "%ld", &num) == 1) {
calculator.addNumber(num);
for (auto pp : p) {
printf("%d: %ld, ", pp, calculator.getPercentile(pp));
}
printf("\n");
}

return 0;
}

0 comments on commit c8a8a29

Please sign in to comment.