Skip to content

Instantly share code, notes, and snippets.

@linxGnu
Created March 14, 2022 00:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linxGnu/e2d0030b22d62a34b86b88050b04920a to your computer and use it in GitHub Desktop.
Save linxGnu/e2d0030b22d62a34b86b88050b04920a to your computer and use it in GitHub Desktop.
// goos: darwin
// goarch: arm64
// pkg: github.com/hashicorp/raft
// BenchmarkTimeAfter-10 436 3896361 ns/op 2152307 B/op 30001 allocs/op
// BenchmarkTimer-10 764 1399790 ns/op 2000058 B/op 30001 allocs/op
// BenchmarkWithoutDefer-10 3362208 356.1 ns/op 0 B/op 0 allocs/op
// BenchmarkWithDefer1-10 406236 2952 ns/op 0 B/op 0 allocs/op
// BenchmarkWithDefer2-10 404098 2956 ns/op 0 B/op 0 allocs/op
const timerBenchAttempt = 10000
func BenchmarkTimeAfter(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for attempt := 0; attempt < timerBenchAttempt; attempt++ {
select {
case <-time.After(50 * time.Millisecond):
default:
}
}
}
}
func BenchmarkTimer(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for attempt := 0; attempt < timerBenchAttempt; attempt++ {
timer := time.NewTimer(50 * time.Millisecond)
select {
case <-timer.C:
default:
timer.Stop()
}
}
}
}
func BenchmarkWithoutDefer(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if ans := withoutDefer(1098); ans != 881296890 {
panic(ans)
}
}
}
func BenchmarkWithDefer1(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if ans := withDefer1(1098); ans != 881296890 {
panic(ans)
}
}
}
func BenchmarkWithDefer2(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if ans := withDefer2(1098); ans != 881296890 {
panic(ans)
}
}
}
func withDefer1(v int) (ans int) {
if v > 1 {
defer func() {
ans *= 2
}()
}
for i := 0; i < v; i++ {
ans += i * i
}
return
}
func withDefer2(v int) (ans int) {
defer func() {
if v > 1 {
ans *= 2
}
}()
for i := 0; i < v; i++ {
ans += i * i
}
return
}
func withoutDefer(v int) (ans int) {
for i := 0; i < v; i++ {
ans += i * i
}
if v > 1 {
ans *= 2
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment