Created
January 13, 2018 13:36
-
-
Save rasky/7ff501d0b6bfc1236321d6787279a293 to your computer and use it in GitHub Desktop.
Revisions
-
rasky created this gist
Jan 13, 2018 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,97 @@ 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) } } }