From aee630b03f48a9f528a4a50e9dcb0fdc8ef20aa5 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Tue, 14 Jul 2020 09:34:50 +0100 Subject: add bench helper --- sort/bench.go | 21 +++++++++++++++++++++ sort/insertion_test.go | 14 +++++++++++--- sort/selection_test.go | 14 +++++++++++--- sort/sorted.go | 12 ++++++++++++ 4 files changed, 55 insertions(+), 6 deletions(-) create mode 100644 sort/bench.go create mode 100644 sort/sorted.go (limited to 'sort') diff --git a/sort/bench.go b/sort/bench.go new file mode 100644 index 0000000..094debd --- /dev/null +++ b/sort/bench.go @@ -0,0 +1,21 @@ +package sort + +import ( + "algorithms/ds" + "fmt" + "testing" +) + +// Avoid compiler optimizations +var benchResult []ds.Comparer + +func benchmark(name string, length int, sort func([]ds.Comparer) []ds.Comparer, 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) +} diff --git a/sort/insertion_test.go b/sort/insertion_test.go index 4b503b8..afec414 100644 --- a/sort/insertion_test.go +++ b/sort/insertion_test.go @@ -5,8 +5,16 @@ import ( "testing" ) -func BenchmarkInsertion1000(b *testing.B) { +func BenchmarkInsertion(b *testing.B) { + benchmark("Insertion", 10, Insertion, b) + benchmark("Insertion", 100, Insertion, b) + benchmark("Insertion", 1000, Insertion, b) +} + +func TestInsertion1000(t *testing.T) { a := ds.RandomIntegers(1000, 1000) - b.ResetTimer() - Insertion(a) + a = Insertion(a) + if !Sorted(a) { + t.Errorf("Array not sorted: %v", a) + } } diff --git a/sort/selection_test.go b/sort/selection_test.go index 3881850..c5d6beb 100644 --- a/sort/selection_test.go +++ b/sort/selection_test.go @@ -5,8 +5,16 @@ import ( "testing" ) -func BenchmarkSelection1000(b *testing.B) { +func BenchmarkSelection(b *testing.B) { + benchmark("Selection", 10, Selection, b) + benchmark("Selection", 100, Selection, b) + benchmark("Selection", 1000, Selection, b) +} + +func TestSelection1000(t *testing.T) { a := ds.RandomIntegers(1000, 1000) - b.ResetTimer() - Selection(a) + a = Selection(a) + if !Sorted(a) { + t.Errorf("Array not sorted: %v", a) + } } diff --git a/sort/sorted.go b/sort/sorted.go new file mode 100644 index 0000000..a24de19 --- /dev/null +++ b/sort/sorted.go @@ -0,0 +1,12 @@ +package sort + +import "algorithms/ds" + +func Sorted(a []ds.Comparer) bool { + for i := len(a) - 1; i > 0; i-- { + if a[i].LowerThan(a[i-1]) { + return false + } + } + return true +} -- cgit v1.2.3