[1] добавлены графики

This commit is contained in:
shalovsa 2026-05-11 17:06:58 +03:00
parent 980da05ed5
commit d0130e9280
4 changed files with 147 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

View File

@ -0,0 +1,128 @@
import csv
import os
try:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
HAS_MPL = True
except ImportError:
HAS_MPL = False
print("⚠️ matplotlib не установлен. Установите: pip install matplotlib")
print(" Графики будут пропущены, таблица результатов выведена в терминал.\n")
CSV_PATH = os.path.join(os.path.dirname(__file__), 'results.csv')
PLOTS_DIR = os.path.dirname(__file__)
def load_results(path):
data = {}
with open(path, newline='', encoding='utf-8') as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
struct, mode, op = row[0], row[1], row[2]
mean = float(row[3])
data[(struct, mode, op)] = mean
return data
STRUCTS = ["LinkedList", "HashTable", "BST"]
MODES = ["случайный", "сортированный"]
OPS = ["insert", "find", "delete"]
COLORS = {"LinkedList": "#4E9AF1", "HashTable": "#F4845F", "BST": "#6BCB77"}
def plot_by_operation(data):
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
fig.suptitle("Сравнение структур данных\n(телефонный справочник, N=10 000)",
fontsize=14, fontweight='bold')
for ax, op in zip(axes, OPS):
x_labels = []
values = []
colors = []
for mode in MODES:
for struct in STRUCTS:
key = (struct, mode, op)
val = data.get(key, 0)
x_labels.append(f"{struct}\n({mode[:4]})")
values.append(val)
colors.append(COLORS[struct])
bars = ax.bar(range(len(values)), values, color=colors,
edgecolor='white', linewidth=0.8)
ax.set_xticks(range(len(x_labels)))
ax.set_xticklabels(x_labels, fontsize=8, rotation=15, ha='right')
ax.set_ylabel("Время (с)", fontsize=9)
ax.set_title(f"Операция: {op}", fontweight='bold')
ax.grid(axis='y', alpha=0.3)
for bar, val in zip(bars, values):
ax.text(bar.get_x() + bar.get_width() / 2,
bar.get_height() + max(values) * 0.01,
f"{val:.4f}",
ha='center', va='bottom', fontsize=7)
patches = [mpatches.Patch(color=c, label=s) for s, c in COLORS.items()]
fig.legend(handles=patches, loc='lower center', ncol=3,
bbox_to_anchor=(0.5, -0.05))
plt.tight_layout()
out_path = os.path.join(PLOTS_DIR, 'comparison_by_operation.png')
plt.savefig(out_path, dpi=150, bbox_inches='tight')
print(f"✅ График сохранён: {out_path}")
plt.show()
def plot_sorted_vs_random(data):
fig, axes = plt.subplots(1, 3, figsize=(14, 5))
fig.suptitle("Влияние порядка данных на время операций",
fontsize=13, fontweight='bold')
for ax, struct in zip(axes, STRUCTS):
rand_vals = [data.get((struct, "случайный", op), 0) for op in OPS]
sort_vals = [data.get((struct, "сортированный", op), 0) for op in OPS]
x = range(len(OPS))
w = 0.35
bars1 = ax.bar([i - w/2 for i in x], rand_vals, width=w,
label="случайный", color="#4E9AF1", edgecolor='white')
bars2 = ax.bar([i + w/2 for i in x], sort_vals, width=w,
label="сортированный", color="#F4845F", edgecolor='white')
ax.set_xticks(list(x))
ax.set_xticklabels(OPS)
ax.set_title(struct, fontweight='bold')
ax.set_ylabel("Время (с)", fontsize=9)
ax.legend(fontsize=8)
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
out_path = os.path.join(PLOTS_DIR, 'sorted_vs_random.png')
plt.savefig(out_path, dpi=150, bbox_inches='tight')
print(f"✅ График сохранён: {out_path}")
plt.show()
def print_table(data):
print(f"\n{'Структура':<12} {'Режим':<16} {'Операция':<10} {'Время (с)':<12}")
print("-" * 52)
for (struct, mode, op), mean in sorted(data.items()):
print(f"{struct:<12} {mode:<16} {op:<10} {mean:.6f}")
if __name__ == "__main__":
if not os.path.exists(CSV_PATH):
print(f"❌ Файл результатов не найден: {CSV_PATH}")
print(" Сначала запустите: python benchmark.py")
exit(1)
data = load_results(CSV_PATH)
print_table(data)
if HAS_MPL:
plot_by_operation(data)
plot_sorted_vs_random(data)
else:
print("\n💡 Установите matplotlib для графиков:")
print(" pip install matplotlib")

View File

@ -0,0 +1,19 @@
Структура,Режим,Операция,Среднее (с),Замер_1,Замер_2,Замер_3,Замер_4,Замер_5
LinkedList,случайный,insert,2.013381,2.030341,1.985393,2.000117,2.000130,2.050923
LinkedList,случайный,find,0.026258,0.026263,0.027186,0.026271,0.026350,0.025217
LinkedList,случайный,delete,0.015552,0.017207,0.014387,0.015304,0.015317,0.015547
HashTable,случайный,insert,0.014448,0.014376,0.014608,0.015115,0.013931,0.014212
HashTable,случайный,find,0.000161,0.000162,0.000161,0.000161,0.000158,0.000161
HashTable,случайный,delete,0.000088,0.000089,0.000089,0.000088,0.000086,0.000086
BST,случайный,insert,0.015575,0.015822,0.015653,0.015507,0.015398,0.015496
BST,случайный,find,0.000133,0.000135,0.000133,0.000131,0.000133,0.000133
BST,случайный,delete,0.000100,0.000104,0.000100,0.000100,0.000099,0.000099
LinkedList,сортированный,insert,1.890415,1.937600,1.916341,1.863388,1.872563,1.862181
LinkedList,сортированный,find,0.023136,0.030373,0.021794,0.021670,0.020861,0.020980
LinkedList,сортированный,delete,0.014986,0.017694,0.014155,0.014365,0.014293,0.014424
HashTable,сортированный,insert,0.017723,0.015734,0.019191,0.019721,0.015843,0.018128
HashTable,сортированный,find,0.000223,0.000263,0.000206,0.000226,0.000154,0.000264
HashTable,сортированный,delete,0.000125,0.000144,0.000112,0.000132,0.000094,0.000141
BST,сортированный,insert,3.535999,3.577140,3.570114,3.581931,3.485064,3.465746
BST,сортированный,find,0.030666,0.030318,0.033654,0.030108,0.029537,0.029713
BST,сортированный,delete,0.038312,0.037349,0.040109,0.037735,0.036555,0.039810
1 Структура Режим Операция Среднее (с) Замер_1 Замер_2 Замер_3 Замер_4 Замер_5
2 LinkedList случайный insert 2.013381 2.030341 1.985393 2.000117 2.000130 2.050923
3 LinkedList случайный find 0.026258 0.026263 0.027186 0.026271 0.026350 0.025217
4 LinkedList случайный delete 0.015552 0.017207 0.014387 0.015304 0.015317 0.015547
5 HashTable случайный insert 0.014448 0.014376 0.014608 0.015115 0.013931 0.014212
6 HashTable случайный find 0.000161 0.000162 0.000161 0.000161 0.000158 0.000161
7 HashTable случайный delete 0.000088 0.000089 0.000089 0.000088 0.000086 0.000086
8 BST случайный insert 0.015575 0.015822 0.015653 0.015507 0.015398 0.015496
9 BST случайный find 0.000133 0.000135 0.000133 0.000131 0.000133 0.000133
10 BST случайный delete 0.000100 0.000104 0.000100 0.000100 0.000099 0.000099
11 LinkedList сортированный insert 1.890415 1.937600 1.916341 1.863388 1.872563 1.862181
12 LinkedList сортированный find 0.023136 0.030373 0.021794 0.021670 0.020861 0.020980
13 LinkedList сортированный delete 0.014986 0.017694 0.014155 0.014365 0.014293 0.014424
14 HashTable сортированный insert 0.017723 0.015734 0.019191 0.019721 0.015843 0.018128
15 HashTable сортированный find 0.000223 0.000263 0.000206 0.000226 0.000154 0.000264
16 HashTable сортированный delete 0.000125 0.000144 0.000112 0.000132 0.000094 0.000141
17 BST сортированный insert 3.535999 3.577140 3.570114 3.581931 3.485064 3.465746
18 BST сортированный find 0.030666 0.030318 0.033654 0.030108 0.029537 0.029713
19 BST сортированный delete 0.038312 0.037349 0.040109 0.037735 0.036555 0.039810

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB