This commit is contained in:
pogodinda 2026-05-21 20:29:55 +03:00
parent aca0eb0c84
commit 1b7ad33278
8 changed files with 436 additions and 0 deletions

133
pogodinda/lab1/benchmark.py Normal file
View File

@ -0,0 +1,133 @@
import time
import random
import csv
import sys
from linked_list_phonebook import *
from hash_table_phonebook import *
from bst_phonebook import *
sys.setrecursionlimit(100000)
def generate_test_data(n=10000):
"""Генерация тестовых данных"""
uniform_records = [(f"User_{i:05d}", f"+7-999-{i:07d}") for i in range(n)]
shuffled_records = uniform_records.copy()
random.shuffle(shuffled_records)
sorted_records = sorted(uniform_records, key=lambda x: x[0])
existing_names = [f"User_{i:05d}" for i in random.sample(range(n), 100)]
non_existing_names = [f"None_{i:05d}" for i in range(10)]
search_names = existing_names + non_existing_names
delete_names = [f"User_{i:05d}" for i in random.sample(range(n), 50)]
return {
'shuffled': shuffled_records,
'sorted': sorted_records,
'search_names': search_names,
'delete_names': delete_names
}
def run_benchmarks():
print("Генерация тестовых данных...")
N = 10000
test_data = generate_test_data(N)
results = []
structures = [
('LinkedList', 'll'),
('HashTable', 'ht'),
('BST', 'bst')
]
modes = [
('случайный', test_data['shuffled']),
('отсортированный', test_data['sorted'])
]
for struct_name, struct_type in structures:
print(f"\n=== Тестирование {struct_name} ===")
for mode_name, records in modes:
print(f" Режим: {mode_name}")
# Создаем структуру и меряем вставку
if struct_type == 'll':
structure = None
start = time.perf_counter()
for name, phone in records:
structure = ll_insert(structure, name, phone)
end = time.perf_counter()
insert_time = end - start
elif struct_type == 'ht':
structure = create_hash_table(5000)
start = time.perf_counter()
for name, phone in records:
ht_insert(structure, name, phone)
end = time.perf_counter()
insert_time = end - start
elif struct_type == 'bst':
structure = None
start = time.perf_counter()
for name, phone in records:
structure = bst_insert(structure, name, phone)
end = time.perf_counter()
insert_time = end - start
print(f" Вставка: {insert_time:.6f} сек")
results.append([struct_name, mode_name, "вставка", insert_time])
# Поиск
start = time.perf_counter()
for name in test_data['search_names']:
if struct_type == 'll':
ll_find(structure, name)
elif struct_type == 'ht':
ht_find(structure, name)
elif struct_type == 'bst':
bst_find(structure, name)
end = time.perf_counter()
find_time = end - start
print(f" Поиск (60 запросов): {find_time:.6f} сек")
results.append([struct_name, mode_name, "поиск", find_time])
# Удаление
start = time.perf_counter()
for name in test_data['delete_names']:
if struct_type == 'll':
structure = ll_delete(structure, name)
elif struct_type == 'ht':
ht_delete(structure, name)
elif struct_type == 'bst':
structure = bst_delete(structure, name)
end = time.perf_counter()
delete_time = end - start
print(f" Удаление (30 записей): {delete_time:.6f} сек")
results.append([struct_name, mode_name, "удаление", delete_time])
# Сохраняем в CSV
with open('docs/data/results.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Структура', 'Режим', 'Операция', 'Время (сек)'])
writer.writerows(results)
print("\n" + "="*60)
print("ИТОГОВЫЕ РЕЗУЛЬТАТЫ (в секундах)")
print("="*60)
print(f"{'Структура':12} {'Режим':12} {'Операция':10} {'Время':>10}")
print("-"*50)
for row in results:
print(f"{row[0]:12} {row[1]:12} {row[2]:10} {row[3]:10.6f}")
print(f"\nРезультаты сохранены в docs/data/results.csv")
if __name__ == "__main__":
random.seed(42)
run_benchmarks()

View File

@ -0,0 +1,66 @@
def create_bst_node(name, phone):
return {'name': name, 'phone': phone, 'left': None, 'right': None}
def bst_insert(root, name, phone):
if root is None:
return create_bst_node(name, phone)
if name < root['name']:
root['left'] = bst_insert(root['left'], name, phone)
elif name > root['name']:
root['right'] = bst_insert(root['right'], name, phone)
else:
root['phone'] = phone
return root
def bst_find(root, name):
if root is None:
return None
if name < root['name']:
return bst_find(root['left'], name)
elif name > root['name']:
return bst_find(root['right'], name)
else:
return root['phone']
def bst_find_min(root):
current = root
while current and current['left'] is not None:
current = current['left']
return current
def bst_delete(root, name):
if root is None:
return None
if name < root['name']:
root['left'] = bst_delete(root['left'], name)
elif name > root['name']:
root['right'] = bst_delete(root['right'], name)
else:
if root['left'] is None:
return root['right']
elif root['right'] is None:
return root['left']
min_node = bst_find_min(root['right'])
root['name'] = min_node['name']
root['phone'] = min_node['phone']
root['right'] = bst_delete(root['right'], min_node['name'])
return root
def bst_list_all(root):
records = []
def inorder_traversal(node):
if node is None:
return
inorder_traversal(node['left'])
records.append((node['name'], node['phone']))
inorder_traversal(node['right'])
inorder_traversal(root)
return records

Binary file not shown.

View File

@ -0,0 +1,19 @@
Структура,Режим,Операция,Время (сек)
LinkedList,случайный,вставка,6.751254200004041
LinkedList,случайный,поиск,0.07962289988063276
LinkedList,случайный,удаление,0.038067599991336465
LinkedList,отсортированный,вставка,7.378327900078148
LinkedList,отсортированный,поиск,0.09230039990507066
LinkedList,отсортированный,удаление,0.023862000089138746
HashTable,случайный,вставка,0.02441199985332787
HashTable,случайный,поиск,0.0002272999845445156
HashTable,случайный,удаление,0.00011650007218122482
HashTable,отсортированный,вставка,0.023515600012615323
HashTable,отсортированный,поиск,0.00027600000612437725
HashTable,отсортированный,удаление,0.00012340000830590725
BST,случайный,вставка,0.03815519995987415
BST,случайный,поиск,0.00031240005046129227
BST,случайный,удаление,0.00018319999799132347
BST,отсортированный,вставка,21.532808099873364
BST,отсортированный,поиск,0.18976689991541207
BST,отсортированный,удаление,0.07795759988948703
Internal Server Error - DRE.lab repo

Internal Server Error

Gitea Version: 1.22.0