You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

107 lines
1.5 KiB

package main
import (
"fmt"
"math"
"math/rand"
"time"
)
type intime struct {
start time.Time
stop time.Time
duration time.Duration
}
const itr int = 1000000
func (i *intime) Start() {
i.start = time.Now()
}
func (i *intime) Stop() {
i.stop = time.Now()
i.duration = i.stop.Sub(i.start)
}
func main() {
rand.Seed(42)
// Matth bench
var matTime intime
matTime.Start()
var nbPrime int
for i := range [itr]int{} {
if isPrime(i) {
nbPrime++
}
}
matTime.Stop()
fmt.Println("Nb prime found: ", nbPrime, "IN", matTime.duration)
// Pointer bench
var ptrTime intime
ptrTime.Start()
mapb := make(map[int]int)
for range [itr * 2]int{} {
mapb[rand.Int()] = rand.Int()
}
ptrTime.Stop()
fmt.Println("Map final len: ", len(mapb), "IN", ptrTime.duration)
// String bench
var strTime intime
strTime.Start()
var str string
for range [itr / 16]int{} {
str = fmt.Sprintf("%s%q", str, rand.Intn(1000))
str += fmt.Sprintf("%q", rand.Intn(1000))
}
strTime.Stop()
fmt.Println("Str final len: ", len(str), "IN", strTime.duration)
// Loop bench
var loopTime intime
loopTime.Start()
var itrLoop int
for range [itr / 1024]int{} {
for range [itr / 512]int{} {
for range [itr / 256]int{} {
itrLoop++
}
}
}
loopTime.Stop()
fmt.Println("Total loop:", itrLoop, "IN", loopTime.duration)
}
func isPrime(ic int) bool {
if ic <= 1 {
return false
}
if ic < 2 {
return false
}
if ic == 2 {
return true
}
for i := 2; i < int(math.Sqrt(float64(ic)))+1; i++ {
if ic%i == 0 {
return false
}
}
return true
}