Skip to content

Instantly share code, notes, and snippets.

@maruel
Created April 11, 2018 14:54
Show Gist options
  • Save maruel/1b99ec768539ffee7cca4aa68b3d9205 to your computer and use it in GitHub Desktop.
Save maruel/1b99ec768539ffee7cca4aa68b3d9205 to your computer and use it in GitHub Desktop.
Benchmarking functions
package main
import (
"fmt"
"testing"
)
func BenchmarkAnonymousFunction(b *testing.B) {
var t int64
for i := 0; i < b.N; i++ {
f := func(j int64) (r int64) {
r = j * 2
return
}
t = f(int64(i))
}
fmt.Sprintln(t)
}
func BenchmarkClosure(b *testing.B) {
var t int64
for i := 0; i < b.N; i++ {
f := func() (r int64) {
r = int64(i) * 2
return
}
t = f()
}
fmt.Sprintln(t)
}
func BenchmarkNormalFunction(b *testing.B) {
var t int64
for i := 0; i < b.N; i++ {
t = multiple2(int64(i))
}
fmt.Sprintln(t)
}
func BenchmarkNormalFunctionNotInline(b *testing.B) {
var t int64
for i := 0; i < b.N; i++ {
t = multiple2NoInline(int64(i))
}
fmt.Sprintln(t)
}
func BenchmarkReturnedFunction(b *testing.B) {
var t int64
f := getFunc()
for i := 0; i < b.N; i++ {
t = f(int64(i))
}
fmt.Sprintln(t)
}
func multiple2(i int64) int64 {
return i * 2
}
//go:noinline
func multiple2NoInline(i int64) int64 {
return i * 2
}
func getFunc() func(int64) int64 {
return func(i int64) int64 {
return i * 2
}
}
$ go test -bench=.
goos: linux
goarch: amd64
pkg: foo
BenchmarkAnonymousFunction-32 2000000000 0.86 ns/op
BenchmarkClosure-32 1000000000 2.26 ns/op
BenchmarkNormalFunction-32 2000000000 0.78 ns/op
BenchmarkNormalFunctionNotInline-32 500000000 2.34 ns/op
BenchmarkReturnedFunction-32 1000000000 2.36 ns/op
PASS
ok foo 10.284s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment