-
-
Save bluescreen10/6776ac37657c3a9be15423fcfa638e35 to your computer and use it in GitHub Desktop.
panic benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"math" | |
"testing" | |
) | |
var ErrDivideByZero error = errors.New("can't divide by zero") | |
const MaxIters = 1000 | |
func BenchmarkDivide(b *testing.B) { | |
p1, p2 := 10000, 2000 | |
callDivide := func(a, b int) int { | |
acc := 0 | |
for j := 0; j < MaxIters; j++ { | |
acc += Divide(a+j, b-j) | |
} | |
return acc | |
} | |
for i := 0; i < b.N; i++ { | |
callDivide(p1, p2) | |
} | |
} | |
func BenchmarkDivide2(b *testing.B) { | |
p1, p2 := 10000, 2000 | |
callDivide := func(a, b int) int { | |
acc := 0 | |
for j := 0; j < MaxIters; j++ { | |
r, _ := Divide2(a+j, b-j) | |
acc += r | |
} | |
return acc | |
} | |
for i := 0; i < b.N; i++ { | |
callDivide(p1, p2) | |
} | |
} | |
func BenchmarkDivide2Check(b *testing.B) { | |
p1, p2 := 10000, 2000 | |
callDivide := func(a, b int) int { | |
acc := 0 | |
for j := 0; j < MaxIters; j++ { | |
r, err := Divide2(a+j, b-j) | |
if err == nil { | |
acc += r | |
} | |
} | |
return acc | |
} | |
for i := 0; i < b.N; i++ { | |
callDivide(p1, p2) | |
} | |
} | |
func BenchmarkPanic(b *testing.B) { | |
p1, p2 := 10000, 2000 | |
callDivide := func(a, b int) int { | |
acc := 0 | |
for j := 0; j < MaxIters; j++ { | |
acc += Divide(a+j, b-j) | |
} | |
return acc | |
} | |
for i := 0; i < b.N; i++ { | |
callDivide(p1, p2) | |
} | |
} | |
func BenchmarkPanicRecover(b *testing.B) { | |
p1, p2 := 10000, 2000 | |
callDivide := func(a, b int) int { | |
defer func() { | |
if r := recover(); r != nil { | |
fmt.Println("error") | |
} | |
}() | |
acc := 0 | |
for j := 0; j < MaxIters; j++ { | |
acc += Divide(a+j, b-j) | |
} | |
return acc | |
} | |
for i := 0; i < b.N; i++ { | |
callDivide(p1, p2) | |
} | |
} | |
//go:noinline | |
func Divide(a, b int) int { | |
if b == 0 || math.Abs(float64(b)) > math.Abs(float64(a)) { | |
return 0 | |
} | |
return a / b | |
} | |
//go:noinline | |
func Divide2(a, b int) (int, error) { | |
if b == 0 || math.Abs(float64(b)) > math.Abs(float64(a)) { | |
return 0, ErrDivideByZero | |
} | |
return a / b, nil | |
} | |
//go:noinline | |
func DividePanic(a, b int) int { | |
if b == 0 || math.Abs(float64(b)) > math.Abs(float64(a)) { | |
panic(ErrDivideByZero) | |
} | |
return a / b | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment