Skip to content

Instantly share code, notes, and snippets.

@mashbridge
Created December 11, 2012 07:19
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 mashbridge/4256541 to your computer and use it in GitHub Desktop.
Save mashbridge/4256541 to your computer and use it in GitHub Desktop.
// For large numbers of math.Pow(x,y) calls, it's worth special-casing y=2
// and squaring it yourself.
package main
import (
"flag"
"fmt"
"math"
)
var use_math = flag.Bool("m", false, "")
const limit = 1000 * 1000 * 100
func main() {
flag.Parse()
if *use_math {
fmt.Println("using math.Pow")
for i := 0; i < limit; i++ {
math.Pow(float64(i), 2)
}
} else {
fmt.Println("using multiplication")
for i := 0; i < limit; i++ {
_ = i * i
}
}
}
/*
On a recent MacBook Pro:
$ time go run pow.go
using multiplication
real 0m0.336s
user 0m0.293s
sys 0m0.034s
$ time go run pow.go -m
using math.Pow
real 0m6.707s
user 0m6.667s
sys 0m0.030s
On a 2005-vintage MacBookPro:
$ time go run pow.go
using multiplication
real 0m0.638s
user 0m0.507s
sys 0m0.069s
$ time go run pow.go -m
using math.Pow
real 0m13.098s
user 0m12.949s
sys 0m0.084s
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment