I did a speed comparison of different methods using math/rand package from stdlib and github.com/MichaelTJones/pcg, another pseudorandom number generator in go
Here is the code I used for timing the different variants:
package main
import (
"fmt"
"math/rand"
"testing"
"github.com/MichaelTJones/pcg"
)
func BenchmarkBool(b *testing.B) {
pcg32 := pcg.NewPCG32()
ff := []func() bool{
func() bool { return rand.Intn(2) == 0 }, // 1
func() bool { return rand.Int31n(2) == 0 }, // 2
func() bool { return rand.Int63n(2) == 0 }, // 3
func() bool { return rand.Float32() < .5 }, // 4
func() bool { return rand.Float64() < .5 }, // 5
func() bool { return rand.Int31()&(1<<30) == 0 }, // 6
func() bool { return rand.Uint32()&(1<<31) == 0 }, // 7
func() bool { return rand.Int63()&(1<<62) == 0 }, // 8
func() bool { return rand.Uint64()&(1<<63) == 0 }, // 9
func() bool { return pcg32.Random()&0x01 == 0 }, // 10
}
for i, f := range ff {
b.Run(fmt.Sprintf("method%v", i+1), func(b *testing.B) {
for n := 0; n < b.N; n++ {
_ = f()
}
})
}
}
On my machine, the output of this program is
BenchmarkBool/method1-4 50000000 36.8 ns/op
BenchmarkBool/method2-4 50000000 34.7 ns/op
BenchmarkBool/method3-4 50000000 31.5 ns/op
BenchmarkBool/method4-4 50000000 33.3 ns/op
BenchmarkBool/method5-4 50000000 30.1 ns/op
BenchmarkBool/method6-4 50000000 29.4 ns/op
BenchmarkBool/method7-4 50000000 31.0 ns/op
BenchmarkBool/method8-4 50000000 28.7 ns/op
BenchmarkBool/method9-4 50000000 29.5 ns/op
BenchmarkBool/method10-4 300000000 4.86 ns/op
i.e. method number 10 is fastest, and number 1 is slowest.