Skip to content

Instantly share code, notes, and snippets.

@joshlf
Created August 17, 2016 20:17
Show Gist options
  • Save joshlf/2fc41e13ff18debb48a6a2c3539c8523 to your computer and use it in GitHub Desktop.
Save joshlf/2fc41e13ff18debb48a6a2c3539c8523 to your computer and use it in GitHub Desktop.
package sort
import (
"math/rand"
"sort"
"testing"
)
func TestSort(t *testing.T) {
for i := 0; i < 100; i++ {
ints := rand.Perm(100)
Sort(ints, func(i, j *int) bool { return *i < *j })
if !sort.IntsAreSorted(ints) {
t.Errorf("invalid sort: %v", ints)
}
}
}
func BenchmarkSort(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
ints := rand.Perm(100)
b.StartTimer()
Sort(ints, func(i, j *int) bool { return *i < *j })
}
}
func BenchmarkNativeSort(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
ints := sortableInts(rand.Perm(100))
b.StartTimer()
sort.Sort(ints)
}
}
func BenchmarkSortPerOp(b *testing.B) {
ints := rand.Perm(b.N)
b.ResetTimer()
Sort(ints, func(i, j *int) bool { return *i < *j })
}
func BenchmarkNativeSortPerOp(b *testing.B) {
ints := sortableInts(rand.Perm(b.N))
b.ResetTimer()
sort.Sort(ints)
}
type sortableInts []int
func (s sortableInts) Len() int { return len(s) }
func (s sortableInts) Less(i, j int) bool { return s[i] < s[j] }
func (s sortableInts) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment