CUCHULAIN:
package main
import (
"fmt"
"math"
"math/rand"
"strconv"
"time"
"gonum.org/v1/gonum/stat"
)
func main() {
rand.Seed(time.Now().Unix())
flt := rand.Float64() * 1e20
rand.Seed(time.Now().Unix())
flt = flt + rand.Float64()*1e10
rand.Seed(time.Now().Unix())
flt = flt + rand.Float64()
plc := rand.Intn(9)
num := 100
fmt.Println(flt, plc, Rounder(flt, plc))
fmt.Println(flt, plc, Rounderp(flt, plc))
fmt.Println()
fn1 := Measurer(num, Rounder, flt, plc)
fmt.Println("Rounder times:", fn1)
fmt.Println("Rounder mean time:", stat.Mean(fn1, nil))
fmt.Println()
fn2 := Measurer(num, Rounderp, flt, plc)
fmt.Println("Rounderp times:", fn2)
fmt.Println("Rounderp mean time:", stat.Mean(fn2, nil))
}
func Measurer(num int, fn func(par float64, places int) float64, p1 float64, plc int) []float64 {
var ott []float64
for i := 0; i < num; i++ {
t0 := time.Now()
fn(p1, plc)
t1 := float64(time.Since(t0))
ott = append(ott, t1)
}
return ott
}
func Rounder(i float64, places int) float64 {
frmt := "%." + fmt.Sprint(places) + "f"
a, _ := strconv.ParseFloat(fmt.Sprintf(frmt, i), 64)
return a
}
func Rounderp(i float64, places int) float64 {
pow := math.Pow10(places)
num := math.Round(i*pow) / pow
return num
}
Ten tvuj zpusob je 20x rychlejsi dle horejsiho testu. :)