Skip to content

Instantly share code, notes, and snippets.

@zach-klippenstein
Last active August 29, 2015 14:09
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 zach-klippenstein/b29936061804481bcaa5 to your computer and use it in GitHub Desktop.
Save zach-klippenstein/b29936061804481bcaa5 to your computer and use it in GitHub Desktop.
Float Comparison Benchmark: Subtraction vs Multiplication
package main
import (
"math"
"math/rand"
"runtime"
"testing"
)
const DELTA_MULT = 10000000000
const DELTA_SUB = 0.00000001
func init() {
runtime.GOMAXPROCS(1)
}
func compareMult(a float64, b float64, delta float64) bool {
return int64(a*delta) == int64(b*delta)
}
func compareSub(a float64, b float64, delta float64) bool {
return math.Abs(a-b) < delta
}
func BenchmarkMultiplication(b *testing.B) {
float1 := rand.Float64()
float2 := rand.Float64()
b.ResetTimer()
for i := 0; i < b.N; i++ {
compareMult(float1, float2, DELTA_MULT)
}
}
func BenchmarkSubtraction(b *testing.B) {
float1 := rand.Float64()
float2 := rand.Float64()
b.ResetTimer()
for i := 0; i < b.N; i++ {
compareSub(float1, float2, DELTA_SUB)
}
}
@zach-klippenstein
Copy link
Author

Results on a 2014 MacBook Pro with a 2.6 GHz Core i5:

$ go test -bench .
testing: warning: no tests to run
PASS
BenchmarkMultiplication 2000000000           1.36 ns/op
BenchmarkSubtraction    500000000            5.55 ns/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment