comment shit out in 2

This commit is contained in:
2026-04-28 15:52:29 +07:00
parent 85c625a74a
commit 335769a10e
+76 -35
View File
@@ -8,43 +8,47 @@
#include <unistd.h> #include <unistd.h>
#include <sstream> #include <sstream>
constexpr int NIL = -1; constexpr int NIL = -1; // Маркер конца списка (аналог nullptr для индексов)
// Структура узла списка, хранящегося в массиве
struct Node { struct Node {
int value; int value; // Значение элемента
int next; int next; // Индекс следующего элемента в массиве pool
}; };
// Результат работы функции сортировки
struct SortResult { struct SortResult {
int head; int head; // Индекс головы отсортированного списка
long long comparisons; long long comparisons; // Счетчик выполненных сравнений
}; };
// Аргументы для передачи в новый поток
struct Args { struct Args {
Node* pool; Node* pool; // Указатель на массив всех узлов
int head; int head; // Голова подсписка для сортировки
int depth; int depth; // Текущая глубина рекурсии
int size; int size; // Количество элементов в подсписке
int threshold; int threshold; // Порог, ниже которого новые потоки не создаются
SortResult* res_out; SortResult* res_out; // Куда записать результат работы потока
}; };
int active_threads = 0; // Глобальные переменные для управления потоками
int max_threads = 4; int active_threads = 0; // Текущее количество работающих потоков
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; int max_threads = 4; // Максимально допустимое количество потоков
pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; // Мьютекс для счетчика потоков
bool enable_logging = false; pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; // Мьютекс для синхронизации вывода
bool enable_logging = false; // Флаг включения логирования
// Высокоточное логирование для exporter.py // Логирование событий для анализа производительности
void log_event(const std::string& type, int head, int depth) { void log_event(const std::string& type, int head, int depth) {
if (!enable_logging) return; if (!enable_logging) return;
pthread_mutex_lock(&log_mutex); pthread_mutex_lock(&log_mutex); // Блокируем вывод, чтобы строки не перемешались
timeval tv{}; timeval tv{};
gettimeofday(&tv, nullptr); gettimeofday(&tv, nullptr);
double current_time = tv.tv_sec + tv.tv_usec * 1e-6; double current_time = tv.tv_sec + tv.tv_usec * 1e-6;
std::cout << type << " TID=" << pthread_self() std::cout << type << " TID=" << pthread_self() // ID текущего потока
<< " depth=" << depth << " depth=" << depth
<< " range=[" << head << "," << head << "]" << " range=[" << head << "," << head << "]"
<< " time=" << std::fixed << std::setprecision(6) << current_time << std::endl; << " time=" << std::fixed << std::setprecision(6) << current_time << std::endl;
@@ -52,6 +56,7 @@ void log_event(const std::string& type, int head, int depth) {
pthread_mutex_unlock(&log_mutex); pthread_mutex_unlock(&log_mutex);
} }
// Разделение списка на две равные части (алгоритм "черепахи и зайца")
void split_list(Node* pool, int head, int& left, int& right) { void split_list(Node* pool, int head, int& left, int& right) {
if (head == NIL || pool[head].next == NIL) { if (head == NIL || pool[head].next == NIL) {
left = head; right = NIL; return; left = head; right = NIL; return;
@@ -59,55 +64,75 @@ void split_list(Node* pool, int head, int& left, int& right) {
int slow = head, fast = pool[head].next; int slow = head, fast = pool[head].next;
while (fast != NIL) { while (fast != NIL) {
fast = pool[fast].next; fast = pool[fast].next;
if (fast != NIL) { slow = pool[slow].next; fast = pool[fast].next; } if (fast != NIL) {
slow = pool[slow].next;
fast = pool[fast].next;
}
} }
left = head; left = head;
right = pool[slow].next; right = pool[slow].next;
pool[slow].next = NIL; pool[slow].next = NIL; // Разрываем список на две части
} }
// Слияние двух отсортированных списков
SortResult merge_lists(Node* pool, int l, int r) { SortResult merge_lists(Node* pool, int l, int r) {
long long comps = 0; long long comps = 0;
if (l == NIL) return {r, 0}; if (l == NIL) return {r, 0};
if (r == NIL) return {l, 0}; if (r == NIL) return {l, 0};
int res_head = NIL, tail = NIL; int res_head = NIL, tail = NIL;
// Вспомогательная лямбда для добавления элемента в результирующий список
auto append = [&](int idx) { auto append = [&](int idx) {
if (res_head == NIL) res_head = tail = idx; if (res_head == NIL) res_head = tail = idx;
else { pool[tail].next = idx; tail = idx; } else { pool[tail].next = idx; tail = idx; }
}; };
while (l != NIL && r != NIL) { while (l != NIL && r != NIL) {
comps++; comps++;
if (pool[l].value <= pool[r].value) { int n = pool[l].next; append(l); l = n; } if (pool[l].value <= pool[r].value) {
else { int n = pool[r].next; append(r); r = n; } int n = pool[l].next; append(l); l = n;
} else {
int n = pool[r].next; append(r); r = n;
}
} }
// Прикрепляем оставшиеся элементы
if (l != NIL) pool[tail].next = l; if (l != NIL) pool[tail].next = l;
if (r != NIL) pool[tail].next = r; if (r != NIL) pool[tail].next = r;
return {res_head, comps}; return {res_head, comps};
} }
// Прототип функции для использования в thread_func
SortResult parallel_list_sort(Node* pool, int head, int depth, int size, int threshold); SortResult parallel_list_sort(Node* pool, int head, int depth, int size, int threshold);
// Функция-обертка для запуска в pthread
void* thread_func(void* arg) { void* thread_func(void* arg) {
Args* a = (Args*)arg; Args* a = (Args*)arg;
// Выполняем сортировку и записываем результат по указателю
*(a->res_out) = parallel_list_sort(a->pool, a->head, a->depth, a->size, a->threshold); *(a->res_out) = parallel_list_sort(a->pool, a->head, a->depth, a->size, a->threshold);
return nullptr; return nullptr;
} }
// Основная рекурсивная функция параллельной сортировки
SortResult parallel_list_sort(Node* pool, int head, int depth, int size, int threshold) { SortResult parallel_list_sort(Node* pool, int head, int depth, int size, int threshold) {
log_event("START", head, depth); log_event("START", head, depth);
// Базовый случай рекурсии: список пуст или из одного элемента
if (head == NIL || pool[head].next == NIL) { if (head == NIL || pool[head].next == NIL) {
log_event("END", head, depth); log_event("END", head, depth);
return {head, 0}; return {head, 0};
} }
int left_p, right_p; int left_p, right_p;
split_list(pool, head, left_p, right_p); split_list(pool, head, left_p, right_p); // Разбиваем список
int new_size = size / 2; int new_size = size / 2;
pthread_t tid; pthread_t tid;
bool spawned = false; bool spawned = false; // Флаг: был ли создан новый поток
SortResult res_right = {NIL, 0}; SortResult res_right = {NIL, 0};
// Решаем, нужно ли создавать новый поток
if (size > threshold) { if (size > threshold) {
pthread_mutex_lock(&counter_mutex); pthread_mutex_lock(&counter_mutex);
if (active_threads < max_threads) { if (active_threads < max_threads) {
@@ -118,20 +143,26 @@ SortResult parallel_list_sort(Node* pool, int head, int depth, int size, int thr
} }
if (spawned) { if (spawned) {
// Создаем поток для правой части
Args* args = new Args{pool, right_p, depth + 1, new_size, threshold, &res_right}; Args* args = new Args{pool, right_p, depth + 1, new_size, threshold, &res_right};
pthread_create(&tid, nullptr, thread_func, args); pthread_create(&tid, nullptr, thread_func, args);
// Левую часть сортируем в текущем потоке
SortResult res_left = parallel_list_sort(pool, left_p, depth + 1, new_size, threshold); SortResult res_left = parallel_list_sort(pool, left_p, depth + 1, new_size, threshold);
// Дожидаемся завершения правого потока
pthread_join(tid, nullptr); pthread_join(tid, nullptr);
pthread_mutex_lock(&counter_mutex); pthread_mutex_lock(&counter_mutex);
active_threads--; active_threads--; // Освобождаем место для новых потоков
pthread_mutex_unlock(&counter_mutex); pthread_mutex_unlock(&counter_mutex);
SortResult m = merge_lists(pool, res_left.head, res_right.head); SortResult m = merge_lists(pool, res_left.head, res_right.head);
delete args; delete args; // Очищаем память, выделенную под аргументы
log_event("END", m.head, depth); log_event("END", m.head, depth);
return {m.head, res_left.comparisons + res_right.comparisons + m.comparisons}; return {m.head, res_left.comparisons + res_right.comparisons + m.comparisons};
} else { } else {
// Последовательная сортировка обеих частей в текущем потоке
SortResult res_left = parallel_list_sort(pool, left_p, depth + 1, new_size, threshold); SortResult res_left = parallel_list_sort(pool, left_p, depth + 1, new_size, threshold);
SortResult res_r_seq = parallel_list_sort(pool, right_p, depth + 1, new_size, threshold); SortResult res_r_seq = parallel_list_sort(pool, right_p, depth + 1, new_size, threshold);
SortResult m = merge_lists(pool, res_left.head, res_r_seq.head); SortResult m = merge_lists(pool, res_left.head, res_r_seq.head);
@@ -141,29 +172,39 @@ SortResult parallel_list_sort(Node* pool, int head, int depth, int size, int thr
} }
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
int n = 100000; int n = 100000; // Размер списка по умолчанию
int threshold = 5000; int threshold = 5000; // Порог распараллеливания по умолчанию
// Считывание параметров из командной строки
if (argc >= 2) n = std::atoi(argv[1]); if (argc >= 2) n = std::atoi(argv[1]);
if (argc >= 3) max_threads = std::atoi(argv[2]); if (argc >= 3) max_threads = std::atoi(argv[2]);
if (argc >= 4) threshold = std::atoi(argv[3]); if (argc >= 4) threshold = std::atoi(argv[3]);
// Включаем логи только для маленьких N // Включаем подробные логи только для небольших задач, чтобы не спамить в консоль
if (n < 5000) enable_logging = true; if (n < 5000) enable_logging = true;
// Инициализация пула узлов
std::vector<Node> pool(n); std::vector<Node> pool(n);
std::mt19937 rng(1337); std::mt19937 rng(1337); // Фиксированный seed для воспроизводимости
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
pool[i].value = rng() % 100000; pool[i].value = rng() % 100000;
pool[i].next = (i == n - 1) ? NIL : i + 1; pool[i].next = (i == n - 1) ? NIL : i + 1;
} }
timeval t1, t2; timeval t1, t2;
gettimeofday(&t1, nullptr); gettimeofday(&t1, nullptr); // Замер времени начала
SortResult final_res = parallel_list_sort(pool.data(), 0, 0, n, threshold);
gettimeofday(&t2, nullptr);
// Запуск основной функции сортировки
SortResult final_res = parallel_list_sort(pool.data(), 0, 0, n, threshold);
gettimeofday(&t2, nullptr); // Замер времени окончания
// Расчет и вывод статистики
double elapsed = (t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec) * 1e-6; double elapsed = (t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec) * 1e-6;
std::cerr << "STAT: threads=" << max_threads << " size=" << n << " threshold=" << threshold << " time=" << elapsed << std::endl; std::cerr << "STAT: threads=" << max_threads
<< " size=" << n
<< " threshold=" << threshold
<< " time=" << elapsed << " sec" << std::endl;
return 0; return 0;
} }