Skip to content

Instantly share code, notes, and snippets.

@jasonkeene
Created November 25, 2017 16:59
Show Gist options
  • Save jasonkeene/3c4d20275ca5c131e63c5f34f0a03815 to your computer and use it in GitHub Desktop.
Save jasonkeene/3c4d20275ca5c131e63c5f34f0a03815 to your computer and use it in GitHub Desktop.
Stable Sort Benchmarks
package main
import (
"math/rand"
"sort"
"testing"
)
func benchSort(size int, b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
d := randomInts(size)
b.StartTimer()
sort.Slice(d, func(i, j int) bool { return d[i] < d[j] })
b.StopTimer()
}
}
func benchSortStable(size int, b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
d := randomInts(size)
b.StartTimer()
sort.SliceStable(d, func(i, j int) bool { return d[i] < d[j] })
b.StopTimer()
}
}
func BenchmarkSort100(b *testing.B) { benchSort(100, b) }
func BenchmarkSort1000(b *testing.B) { benchSort(1000, b) }
func BenchmarkSort10000(b *testing.B) { benchSort(10000, b) }
func BenchmarkSortStable100(b *testing.B) { benchSortStable(100, b) }
func BenchmarkSortStable1000(b *testing.B) { benchSortStable(1000, b) }
func BenchmarkSortStable10000(b *testing.B) { benchSortStable(10000, b) }
func randomInts(len int) []int {
d := make([]int, 0, len)
for i := 0; i < len; i++ {
d = append(d, rand.Int())
}
return d
}
$ go test -run=XXX -bench .
BenchmarkSort100-8 200000 6631 ns/op
BenchmarkSort1000-8 10000 159002 ns/op
BenchmarkSort10000-8 500 2432516 ns/op
BenchmarkSortStable100-8 100000 11626 ns/op
BenchmarkSortStable1000-8 10000 215194 ns/op
BenchmarkSortStable10000-8 500 3276896 ns/op
PASS
ok bench_sort 16.221s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment