-
-
Save k2wanko/d650563261903641167e3e4bfad2e2d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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