diff --git a/ivanchenkoam/laba1.txt b/ivanchenkoam/laba1.txt index eb68b99..43ffaa5 100644 --- a/ivanchenkoam/laba1.txt +++ b/ivanchenkoam/laba1.txt @@ -423,3 +423,115 @@ def save_results(results: List[List], filename: str = "results.csv"): writer = csv.writer(f) writer.writerows(results) print(f"\nРезультаты сохранены в {filename}") +def plot_results(results_file: str = "results.csv"): + """Построение графика сравнения производительности""" + import matplotlib.pyplot as plt + import numpy as np + + # Чтение результатов из CSV + data = {} + with open(results_file, 'r', encoding='utf-8') as f: + reader = csv.reader(f) + header = next(reader) # пропускаем заголовок + + for row in reader: + structure = row[0] + mode = row[1] + operation = row[2] + # Берём последнюю колонку (Среднее) + avg_time = float(row[-1]) + + if structure not in data: + data[structure] = {} + if mode not in data[structure]: + data[structure][mode] = {} + + data[structure][mode][operation] = avg_time + + # Настройка стиля + plt.style.use('seaborn-v0_8-darkgrid') + fig, axes = plt.subplots(1, 3, figsize=(15, 5)) + colors = ['#FF6B6B', '#4ECDC4'] + + structures = ["LinkedList", "HashTable", "BST"] + modes = ["shuffled", "sorted"] + operations = ["вставка", "поиск", "удаление"] + op_titles = ["ВСТАВКИ", "ПОИСКА (110 запросов)", "УДАЛЕНИЯ (50 записей)"] + + for idx, (op, op_title) in enumerate(zip(operations, op_titles)): + ax = axes[idx] + x = np.arange(len(structures)) + width = 0.35 + + shuffled_vals = [data[s]['shuffled'][op] for s in structures] + sorted_vals = [data[s]['sorted'][op] for s in structures] + + bars1 = ax.bar(x - width/2, shuffled_vals, width, + label='Случайный порядок', color=colors[0]) + bars2 = ax.bar(x + width/2, sorted_vals, width, + label='Отсортированный порядок', color=colors[1]) + + ax.set_xlabel('Структура данных') + ax.set_ylabel('Время (секунды)') + ax.set_title(f'Сравнение времени {op_title}') + ax.set_xticks(x) + ax.set_xticklabels(['Связный\nсписок', 'Хеш-\nтаблица', 'Двоичное\nдерево']) + ax.legend() + + # Добавляем значения на столбцы + for bars in [bars1, bars2]: + for bar in bars: + height = bar.get_height() + fmt = '{:.4f}'.format(height) if op == 'вставка' else '{:.6f}'.format(height) + ax.text(bar.get_x() + bar.get_width()/2., height, + fmt, ha='center', va='bottom', fontsize=8) + + plt.tight_layout() + plt.savefig('performance_comparison.png', dpi=150, bbox_inches='tight') + plt.show() + + # Вывод сводной таблицы в консоль + print("\n" + "=" * 90) + print("СВОДНАЯ ТАБЛИЦА РЕЗУЛЬТАТОВ (среднее время в секундах)") + print("=" * 90) + print(f"{'Структура':<15} {'Режим':<12} {'Вставка':<14} {'Поиск':<14} {'Удаление':<14}") + print("-" * 90) + + for structure in structures: + for mode in modes: + print(f"{structure:<15} {mode:<12} " + f"{data[structure][mode]['вставка']:<14.6f} " + f"{data[structure][mode]['поиск']:<14.6f} " + f"{data[structure][mode]['удаление']:<14.6f}") + + print("=" * 90) +def main(): + print("=" * 60) + print("ЭКСПЕРИМЕНТАЛЬНОЕ СРАВНЕНИЕ СТРУКТУР ДАННЫХ") + print("Связный список | Хеш-таблица | Двоичное дерево поиска") + print("=" * 60) + + # Запуск эксперимента (5 прогонов) + results = run_experiment(n_records=10000, n_runs=5) + + # Сохранение результатов + save_results(results) + + # Построение графика + try: + import matplotlib.pyplot as plt + print("\nПостроение графика...") + plot_results("results.csv") + + except ImportError: + print("\nВНИМАНИЕ: Библиотека matplotlib не установлена.") + print("Для построения графика выполните: pip install matplotlib") + print("Результаты сохранены в CSV файл, вы можете построить график в Excel.") + + print("\n" + "=" * 60) + print("ЭКСПЕРИМЕНТ ЗАВЕРШЁН") + print("=" * 60) + + +if __name__ == "__main__": + main()