Skip to content

Instantly share code, notes, and snippets.

@linxGnu
Last active June 14, 2018 03:52
Show Gist options
  • Save linxGnu/95e4088c32b4b1f8dc75824e17a680fb to your computer and use it in GitHub Desktop.
Save linxGnu/95e4088c32b4b1f8dc75824e17a680fb to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
const (
numberOperations = 100000000
)
func withoutDefer(i int) (a int) {
if i&1 == 0 {
a = i
} else {
a = i << 1
}
return
}
func withDefer(i int) (a int) {
defer func() {
if i&1 == 0 {
a = i
} else {
a = i << 1
}
}()
return
}
func conditionalDefer(i int) (a int) {
if i&1 == 0 {
defer func() {
a = i
}()
} else {
defer func() {
a = i << 1
}()
}
return
}
func doubleDefer(i int) (a int) {
defer func() {
if i&1 == 0 {
a = i
} else {
a = i << 1
}
}()
defer func() {
a = 3
}()
return
}
func tripleDefer(i int) (a int) {
defer func() {
if i&1 == 0 {
a = i
} else {
a = i << 1
}
}()
defer func() {
a = 4
}()
defer func() {
a = 3
}()
return
}
func main() {
fmt.Printf("Bench with %d number of operations\n", numberOperations)
start := time.Now()
var total uint64
for i := 0; i < numberOperations; i++ {
total += uint64(withoutDefer(i))
}
d1 := time.Now().Sub(start).Seconds()
fmt.Printf("Without defer: %.3f(s) %.3f(op/s)\n", d1, float64(numberOperations)/d1)
start, total = time.Now(), 0
for i := 0; i < numberOperations; i++ {
total += uint64(withDefer(i))
}
d2 := time.Now().Sub(start).Seconds()
fmt.Printf("With defer: %.3f(s) %.3f(op/s)\n", d2, float64(numberOperations)/d2)
start, total = time.Now(), 0
for i := 0; i < numberOperations; i++ {
total += uint64(conditionalDefer(i))
}
d3 := time.Now().Sub(start).Seconds()
fmt.Printf("Conditional defer: %.3f(s) %.3f(op/s)\n", d3, float64(numberOperations)/d3)
start, total = time.Now(), 0
for i := 0; i < numberOperations; i++ {
total += uint64(doubleDefer(i))
}
d4 := time.Now().Sub(start).Seconds()
fmt.Printf("Double defer: %.3f(s) %.3f(op/s)\n", d4, float64(numberOperations)/d4)
start, total = time.Now(), 0
for i := 0; i < numberOperations; i++ {
total += uint64(tripleDefer(i))
}
d5 := time.Now().Sub(start).Seconds()
fmt.Printf("Triple defer: %.3f(s) %.3f(op/s)\n", d5, float64(numberOperations)/d5)
start, total = time.Now(), 0
for i := 0; i < numberOperations; i++ {
total += uint64(doubleDefer(i))
total += uint64(doubleDefer(i))
}
d6 := time.Now().Sub(start).Seconds()
fmt.Printf("Double(x2) defer: %.3f(s) %.3f(op/s)\n", d6, float64(numberOperations)/d6)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment