Skip to content

Instantly share code, notes, and snippets.

@benbjohnson
Last active September 23, 2015 21:25
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 benbjohnson/5d60fba7eafff9c77ccf to your computer and use it in GitHub Desktop.
Save benbjohnson/5d60fba7eafff9c77ccf to your computer and use it in GitHub Desktop.
$ ./bench.test -test.bench=. -test.benchtime=5s -test.cpuprofile=/tmp/cpu.pprof 
testing: warning: no tests to run
PASS
BenchmarkMap-4      	500000000	        15.9 ns/op
--- BENCH: BenchmarkMap-4
	main_test.go:37: result: 100.000000
	main_test.go:37: result: 10000.000000
	main_test.go:37: result: 1000000.000000
	main_test.go:37: result: 100000000.000000
	main_test.go:37: result: 10000000000.000000
	main_test.go:37: result: 50000000000.000000
BenchmarkInterface-4	500000000	        12.6 ns/op
--- BENCH: BenchmarkInterface-4
	main_test.go:54: result: 100.000000
	main_test.go:54: result: 10000.000000
	main_test.go:54: result: 1000000.000000
	main_test.go:54: result: 100000000.000000
	main_test.go:54: result: 10000000000.000000
	main_test.go:54: result: 50000000000.000000
package main_test
import (
"crypto/rand"
"io"
"testing"
)
var Key string
var Map = make(map[string]interface{})
var Value interface{}
func init() {
// Generate key randomly to avoid compiler optimization.
var buf [8]byte
if _, err := io.ReadFull(rand.Reader, buf[:]); err != nil {
panic("crypto read error: " + err.Error())
}
Key = string(buf[:])
// Populate map & interface value.
Map[Key] = float64(100.0)
Value = float64(100.0)
}
func BenchmarkMap(b *testing.B) {
m := make(map[string]interface{})
m[Key] = float64(100.0)
var n float64
for i := 0; i < b.N; i++ {
v, _ := m[Key].(float64)
n += v
}
b.Logf("result: %f", n)
}
func BenchmarkInterface(b *testing.B) {
var m interface{}
m = float64(100.0)
var n float64
for i := 0; i < b.N; i++ {
// Skip maps. This won't happen but we're simulating it.
if _, ok := Value.(map[string]interface{}); ok {
continue
}
v, _ := m.(float64)
n += v
}
b.Logf("result: %f", n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment