Skip to content

Instantly share code, notes, and snippets.

@dgryski
Created December 13, 2016 12:36
Show Gist options
  • Save dgryski/67e6a7ff94c3a1add30eb26ec0ad8b0f to your computer and use it in GitHub Desktop.
Save dgryski/67e6a7ff94c3a1add30eb26ec0ad8b0f to your computer and use it in GitHub Desktop.
<dgryski@kamek[powbench] \ʕ◔ϖ◔ʔ/ > go test -test.bench=.
BenchmarkPolyPow-4 5000000 286 ns/op
BenchmarkPolyFast-4 100000000 16.7 ns/op
PASS
ok github.com/dgryski/powbench 3.430s
package main
import (
"fmt"
"math"
)
func poly(x float64, coeffs ...float64) float64 {
y := coeffs[0]
for i, c := range coeffs[1:] {
y += c * math.Pow(x, float64(i))
}
return y
}
func polyfast(x float64, coeffs ...float64) float64 {
y := coeffs[0]
v := 1.0
for _, c := range coeffs[1:] {
y += c * v
v *= x
}
return y
}
func main() {
var y float64
y = polyfast(2.5, 0.5, 1, 2, 3, 4, 5, 6)
fmt.Printf("fast = %+v\n", y)
y = poly(2.5, 0.5, 1, 2, 3, 4, 5, 6)
fmt.Printf("pow = %+v\n", y)
}
package main
import (
"testing"
)
var sink float64
func BenchmarkPolyPow(b *testing.B) {
for i := 0; i < b.N; i++ {
sink += poly(2.5, 1, 2, 3, 4, 5, 6, 7, 8, 10)
}
}
func BenchmarkPolyFast(b *testing.B) {
for i := 0; i < b.N; i++ {
sink += polyfast(2.5, 1, 2, 3, 4, 5, 6, 7, 8, 10)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment