2026-rff_mp/stepushovgs/data-structures/source/tests/benchmark/main.go
GordStep 62795e88ba Обновление csvwriter
- Функция создания пустого файла
- Разобрался с директорией для сохранения файла
2026-05-13 22:51:35 +03:00

180 lines
4.3 KiB
Go

package main
import (
"fmt"
"math/rand"
csvwriter "source/pkg/csv_writer"
ds "source/pkg/data_struct"
dg "source/pkg/gen_data"
bst "source/pkg/structures/bin_search_tree"
ht "source/pkg/structures/hash_table"
ll "source/pkg/structures/linked_list"
// csv "source/pkg/csv_ri"
"time"
)
const (
countUsers = 10_000
countRepeat = 5
countRandomSearch = 100
countNotExitstSearch = 10
countDeletes = 50
)
type TestData struct {
Items []ds.MyData // все записи
ItemsSorted []ds.MyData // все записи отсортированные
Existing []ds.MyData // для поиска (существующие)
NonExisting []ds.MyData // для поиска (несуществующие)
ToDelete []ds.MyData // для удаления
}
type DataStructure interface {
Insert(data ds.MyData)
Search(name string) (string, bool)
Delete(name string) bool
Len() int
}
// Создатели структур
type StructureFactory func() DataStructure
func NewLinkedList() DataStructure {
return ll.NewLinkedList()
}
func NewHashTable() DataStructure {
return ht.NewHashTable(256, 0.75)
}
func NewBinSearchTree() DataStructure {
return bst.NewBinSearchTree()
}
func uniqueElements(data []ds.MyData) []ds.MyData {
res := make([]ds.MyData, 0, len(data))
isUnique := true
for _, el := range data {
for _, resEl := range res {
if el == resEl {
isUnique = false
break
}
}
if isUnique {
res = append(res, el)
}
}
return res
}
func GenerateTestData() TestData {
items := dg.RecordsShuffled(countUsers)
itemsSort := ds.QSort(items, 0, len(items)-1)
uniqueItems := uniqueElements(items)
existing := make([]ds.MyData, countRandomSearch)
// notExisting := [countNotExitstSearch]ds.MyData{}
notExisting := make([]ds.MyData, countNotExitstSearch)
toDelete := make([]ds.MyData, countDeletes)
countUniq := len(uniqueItems)
for i := 0; i < countRandomSearch; i++ {
// randInd := rand.Intn(countUsers)
randInd := rand.Intn(countUniq)
existing[i] = uniqueItems[randInd]
// fmt.Println(randInd)
}
for i := 0; i < countNotExitstSearch; i++ {
// randInd := rand.Intn(countUsers)
randInd := rand.Intn(10)
name := fmt.Sprintf("User_%d", randInd)
notExisting[i] = *ds.NewData(name, "")
// fmt.Println(randInd)
}
return TestData{
Items: items,
ItemsSorted: itemsSort,
Existing: existing,
NonExisting: notExisting,
ToDelete: toDelete,
}
}
// Тест вставки массива данных (один раз)
func testOneInsert(structure DataStructure, data []ds.MyData) float64 {
start := time.Now()
for _, item := range data {
structure.Insert(item)
}
return time.Since(start).Seconds()
}
func TestInsert(factory StructureFactory, data []ds.MyData, nameStruct, mode string) {
BenchRes := make([]csvwriter.BenchmarkResult, 0)
allTestTime := time.Now()
averageTime := 0.
// Тест Слчайной вставки
for i := 0; i < countRepeat; i++ {
head := factory()
resTime := testOneInsert(head, data)
averageTime += resTime
BenchRes = append(BenchRes, csvwriter.BenchmarkResult{
Structure: nameStruct,
Mode: mode,
Operation: "Вставка",
Time: resTime,
})
fmt.Printf("%s | Вставка | %s | Время: %f\n", nameStruct, mode, resTime)
// fmt.Println(BenchRes)
}
averageTime = time.Since(allTestTime).Seconds() / countRepeat
BenchRes = append(BenchRes, csvwriter.BenchmarkResult{
Structure: nameStruct,
Mode: mode,
Operation: "Вставка",
Time: averageTime,
})
csvwriter.AppendRaw(BenchRes)
}
func Test(nameStruct string, factory StructureFactory, data TestData) {
// BenchRes := make([]csvwriter.BenchmarkResult, 0)
// allTestTime := time.Now()
TestInsert(factory, data.Items, nameStruct, "Случайный")
TestInsert(factory, data.ItemsSorted, nameStruct, "Отсортированный")
}
func main() {
testData := GenerateTestData()
csvwriter.CreateEmptyCSV("results", "benchmarks.csv")
// head_ll := &ll.LinkedList{}
// head_ht := ht.NewHashTable(256, 0.75)
// head_bst := bst.NewBinSearchTree()
fmt.Println("============= Начало тестов =============")
Test("Связный список", NewLinkedList, testData)
Test("Хеш таблица", NewHashTable, testData)
Test("Бинарное дерево поиска", NewBinSearchTree, testData)
}