diff options
| author | Paul Buetow <paul@buetow.org> | 2020-07-14 09:58:13 +0100 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2020-07-14 09:58:13 +0100 |
| commit | 1a175ce919dddb8d3a58533f3827a105483442c0 (patch) | |
| tree | e18b0936bc06050eb25c883b94ff3732df4b8113 /sort/sort_test.go | |
| parent | 6c598a53d3366d8ff7250bdc1ce29fa4c36ec246 (diff) | |
refactored testing and benchmarking
Diffstat (limited to 'sort/sort_test.go')
| -rw-r--r-- | sort/sort_test.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/sort/sort_test.go b/sort/sort_test.go new file mode 100644 index 0000000..60f8aa3 --- /dev/null +++ b/sort/sort_test.go @@ -0,0 +1,53 @@ +package sort + +import ( + "algorithms/ds" + "fmt" + "testing" +) + +// Store results here to avoid compiler optimizations +var benchResult []ds.Comparer + +const maxLength int = 10000 + +type sortAlgorithm func([]ds.Comparer) []ds.Comparer + +func TestSort(t *testing.T) { + for i := 1; i <= maxLength; i *= 10 { + test("Selection", i, Selection, t) + test("Insertion", i, Insertion, t) + } +} + +func BenchmarkSort(b *testing.B) { + for i := 1; i <= maxLength; i *= 10 { + benchmark("Insertion", i, Insertion, b) + } + for i := 1; i <= maxLength; i *= 10 { + benchmark("Selection", i, Selection, b) + } +} + +func test(name string, length int, sort sortAlgorithm, t *testing.T) { + cb := func(t *testing.T) { + t.Parallel() + a := ds.RandomIntegers(length, length) + a = sort(a) + if !Sorted(a) { + t.Errorf("Array not sorted: %v", a) + } + } + t.Run(fmt.Sprintf("Test%s%d", name, length), cb) +} + +func benchmark(name string, length int, sort sortAlgorithm, b *testing.B) { + cb := func(b *testing.B) { + a := ds.RandomIntegers(length, length) + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchResult = sort(a) + } + } + b.Run(fmt.Sprintf("Benchmark%s%d", name, length), cb) +} |
