Skip to content

Instantly share code, notes, and snippets.

@seriousben
Created March 12, 2020 19:45
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 seriousben/bfb8f97c3716d68caf100d7bb005fdf7 to your computer and use it in GitHub Desktop.
Save seriousben/bfb8f97c3716d68caf100d7bb005fdf7 to your computer and use it in GitHub Desktop.
Golang Random Element Benchmark

golang-benchmark-random-element

output

$ go test -bench=. -test.benchtime=5s
goos: darwin
goarch: amd64
pkg: github.com/seriousben/benchmark-random-element
benchmarkmodulo10-16       	78412443	        69.0 ns/op	       0 b/op	       0 allocs/op
benchmarkmodulo100-16      	78941438	        70.5 ns/op	       0 b/op	       0 allocs/op
benchmarkmodulo1000-16     	87087330	        69.2 ns/op	       0 b/op	       0 allocs/op
benchmarkmodulo10000-16    	83965998	        70.6 ns/op	       0 b/op	       0 allocs/op
benchmarkrand10-16         	339789382	        18.2 ns/op	       0 b/op	       0 allocs/op
benchmarkrand100-16        	347168102	        18.0 ns/op	       0 b/op	       0 allocs/op
benchmarkrand1000-16       	339647118	        18.0 ns/op	       0 b/op	       0 allocs/op
benchmarkrand10000-16      	332768221	        17.7 ns/op	       0 b/op	       0 allocs/op
pass
ok  	github.com/seriousben/benchmark-random-element	56.117
package main
import (
"math/rand"
"testing"
"time"
)
func doModulo(n int) {
_ = time.Now().UnixNano() % int64(n)
}
func BenchmarkModulo10(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
doModulo(10)
}
}
func BenchmarkModulo100(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
doModulo(100)
}
}
func BenchmarkModulo1000(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
doModulo(1000)
}
}
func BenchmarkModulo10000(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
doModulo(10000)
}
}
func doRand(n int) {
_ = rand.Intn(n)
}
func BenchmarkRand10(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
doRand(10)
}
}
func BenchmarkRand100(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
doRand(100)
}
}
func BenchmarkRand1000(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
doRand(1000)
}
}
func BenchmarkRand10000(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
doRand(10000)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment