Skip to content

Instantly share code, notes, and snippets.

@k2wanko
Last active October 4, 2016 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k2wanko/d650563261903641167e3e4bfad2e2d1 to your computer and use it in GitHub Desktop.
Save k2wanko/d650563261903641167e3e4bfad2e2d1 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sort"
"testing"
)
type testT struct {
Name string
Price int
}
type testTSlice []*testT
func (t testTSlice) Len() int {
return len(t)
}
func less(t testTSlice, i, j int) bool {
return t[i].Price < t[j].Price
}
func (t testTSlice) Less(i, j int) bool {
return less(t, i, j)
}
func swap(t testTSlice, i, j int) {
t[i], t[j] = t[j], t[i]
}
func (t testTSlice) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func newTestData(size int) testTSlice {
tests := make(testTSlice, size)
for i := size - 1; i >= 0; i-- {
tests[i] = &testT{
Name: fmt.Sprintf("Item %d", i),
Price: i * 100,
}
}
return tests
}
func BenchmarkSort(b *testing.B) {
tests := make([]testTSlice, b.N)
for i := 0; i < b.N; i++ {
tests[i] = newTestData(1000)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
sort.Sort(tests[i])
}
}
func BenchmarkSlice(b *testing.B) {
tests := make([]testTSlice, b.N)
for i := 0; i < b.N; i++ {
tests[i] = newTestData(1000)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
td := tests[i]
sort.Slice(td, func(i, j int) bool {
return less(td, i, j)
})
}
}
$ GOMAXPROCS=1 GOROOT=~/src/github.com/golang/go go test -bench .
testing: warning: no tests to run
BenchmarkSort 30000 57616 ns/op
BenchmarkSlice 30000 43650 ns/op
PASS
ok github.com/k2wanko/sort-bench 38.994s
$ GOMAXPROCS=1 GOROOT=~/src/github.com/golang/go go test -bench . -benchmem
testing: warning: no tests to run
BenchmarkSort 20000 62222 ns/op 32 B/op 1 allocs/op
BenchmarkSlice 30000 50571 ns/op 64 B/op 2 allocs/op
PASS
ok github.com/k2wanko/sort-bench 37.401s
$ GOMAXPROCS=1 GOROOT=~/src/github.com/golang/go go test -bench . -benchmem
testing: warning: no tests to run
BenchmarkSort 20000 70767 ns/op 32 B/op 1 allocs/op
BenchmarkSlice 20000 69151 ns/op 64 B/op 2 allocs/op
PASS
ok github.com/k2wanko/sort-bench 41.482s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment