Skip to content

Instantly share code, notes, and snippets.

@mipearson
Forked from davecheney/bm_test.go
Last active August 19, 2021 12:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mipearson/79226b266ab901fa74e4 to your computer and use it in GitHub Desktop.
Save mipearson/79226b266ab901fa74e4 to your computer and use it in GitHub Desktop.
Add an increment of a global variable after each op to ensure the Go compiler isn't being clever about optimisation.
package bm
import (
"testing"
)
var mb = map[string]bool{
"alpha": true,
"beta": true,
"gamma": true,
"delta": true,
"epsilon": true,
"zeta": true,
"eta": true,
"theta": true,
"iota": true,
"kappa": true,
"lambda": true,
"mu": true,
"nu": true,
"xi": true,
"omicron": true,
"pi": true,
"rho": true,
"sigma": true,
"tau": true,
"upsilon": true,
"phi": true,
"chi": true,
"psi": true,
"omega": true,
}
var ms = map[string]struct{}{
"alpha": struct{}{},
"beta": struct{}{},
"gamma": struct{}{},
"delta": struct{}{},
"epsilon": struct{}{},
"zeta": struct{}{},
"eta": struct{}{},
"theta": struct{}{},
"iota": struct{}{},
"kappa": struct{}{},
"lambda": struct{}{},
"mu": struct{}{},
"nu": struct{}{},
"xi": struct{}{},
"omicron": struct{}{},
"pi": struct{}{},
"rho": struct{}{},
"sigma": struct{}{},
"tau": struct{}{},
"upsilon": struct{}{},
"phi": struct{}{},
"chi": struct{}{},
"psi": struct{}{},
"omega": struct{}{},
}
var bb int
func inc(truthy bool) {
if truthy {
bb += 1
}
}
func BenchmarkNoOp(B *testing.B) {
bb = 0
for i := 0; i < B.N; i++ {
inc(true)
inc(true)
inc(true)
inc(true)
inc(true)
}
}
func BenchmarkMapBool(B *testing.B) {
bb = 0
var b bool
for i := 0; i < B.N; i++ {
b = mb["alpha"]
inc(b)
b = mb["gamma"]
inc(b)
b = mb["mu"]
inc(b)
b = mb["pi"]
inc(b)
b = mb["omega"]
inc(b)
}
}
func BenchmarkMapStruct(B *testing.B) {
bb = 0
var b bool
for i := 0; i < B.N; i++ {
_, b = ms["alpha"]
inc(b)
_, b = ms["gamma"]
inc(b)
_, b = ms["mu"]
inc(b)
_, b = ms["pi"]
inc(b)
_, b = ms["omega"]
inc(b)
}
}
➜ gobench go test -bench=. -benchtime=10s
testing: warning: no tests to run
PASS
BenchmarkNoOp 2000000000 8.55 ns/op
BenchmarkMapBool 100000000 115 ns/op
BenchmarkMapStruct 100000000 112 ns/op
ok _/Users/mp/gobench 41.027s
➜ gobench go test -bench=. -benchtime=10s
testing: warning: no tests to run
PASS
BenchmarkNoOp 2000000000 8.77 ns/op
BenchmarkMapBool 100000000 114 ns/op
BenchmarkMapStruct 100000000 118 ns/op
ok _/Users/mp/gobench 41.909s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment