Skip to content

Instantly share code, notes, and snippets.

@rasky
Created January 13, 2018 13:36
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 rasky/7ff501d0b6bfc1236321d6787279a293 to your computer and use it in GitHub Desktop.
Save rasky/7ff501d0b6bfc1236321d6787279a293 to your computer and use it in GitHub Desktop.
package abs
import (
"math/rand"
"reflect"
"runtime"
"strings"
"testing"
)
const (
MaxInt int64 = 1<<63 - 1
MinInt int64 = -1 << 63
)
// An absFunc is a function that returns the absolute value of an integer.
type absFunc func(int64) int64
var (
testInputs = []int64{MinInt + 1, MinInt + 2, -1, -0, 1, 2, MaxInt - 1, MaxInt}
testOutputs = []int64{MaxInt, MaxInt - 1, 1, 0, 1, 2, MaxInt - 1, MaxInt}
testFuncs = []absFunc{
WithBranch,
WithStdLib, // test failure expected on large numbers
WithTwosComplement,
WithASM,
}
)
func funcName(v interface{}) string {
s := runtime.FuncForPC(reflect.ValueOf(v).Pointer()).Name()
return s[strings.LastIndex(s, ".")+1:]
}
// func TestAbs(t *testing.T) {
// for _, f := range testFuncs {
// testName := funcName(f)
// t.Run(testName, func(t *testing.T) {
// for i := 0; i < len(testInputs); i++ {
// actual := f(testInputs[i])
// if actual != testOutputs[i] {
// t.Errorf("%s(%d)", testName, testInputs[i])
// t.Errorf(" input: %064b (%d)", uint64(testInputs[i]), testInputs[i])
// t.Errorf(" expected: %064b (%d)", uint64(testOutputs[i]), testOutputs[i])
// t.Errorf(" actual: %064b (%d)", uint64(actual), actual)
// }
// }
// })
// }
// }
func randData(n int) []int64 {
data := make([]int64, n)
for i := range data {
data[i] = rand.Int63() << 1
}
return data
}
func BenchmarkWithBranch(b *testing.B) {
data := randData(1 << 16)
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, x := range data {
WithBranch(x)
}
}
}
func BenchmarkWithStdLib(b *testing.B) {
data := randData(1 << 16)
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, x := range data {
WithStdLib(x)
}
}
}
func BenchmarkWithTwosComplement(b *testing.B) {
data := randData(1 << 16)
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, x := range data {
WithTwosComplement(x)
}
}
}
func BenchmarkWithASM(b *testing.B) {
data := randData(1 << 16)
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, x := range data {
WithASM(x)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment