Created
January 25, 2019 15:00
-
-
Save robmccoll/008bd392c699ac8fae60fa2a746681d1 to your computer and use it in GitHub Desktop.
Go chan bool loop vs. sync.WaitGroup bench
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 ( | |
"sync" | |
"testing" | |
) | |
func immediateWG(wg *sync.WaitGroup) { | |
wg.Done() | |
} | |
func Benchmark0GoRoutineWG(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var wg sync.WaitGroup | |
wg.Wait() | |
} | |
} | |
func Benchmark1GoRoutineWG(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var wg sync.WaitGroup | |
wg.Add(1) | |
go immediateWG(&wg) | |
wg.Wait() | |
} | |
} | |
func Benchmark10GoRoutineWG(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var wg sync.WaitGroup | |
for i := 0; i < 10; i++ { | |
wg.Add(1) | |
go immediateWG(&wg) | |
} | |
wg.Wait() | |
} | |
} | |
func Benchmark100GoRoutineWG(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var wg sync.WaitGroup | |
for i := 0; i < 100; i++ { | |
wg.Add(1) | |
go immediateWG(&wg) | |
} | |
wg.Wait() | |
} | |
} | |
func immediateCh(ch chan bool) { | |
ch <- true | |
} | |
func Benchmark1GoRoutineCh(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
ch := make(chan bool) | |
go immediateCh(ch) | |
<-ch | |
} | |
} | |
func Benchmark10GoRoutineCh(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
ch := make(chan bool) | |
for i := 0; i < 10; i++ { | |
go immediateCh(ch) | |
} | |
for i := 0; i < 10; i++ { | |
<-ch | |
} | |
} | |
} | |
func Benchmark100GoRoutineCh(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
ch := make(chan bool) | |
for i := 0; i < 100; i++ { | |
go immediateCh(ch) | |
} | |
for i := 0; i < 100; i++ { | |
<-ch | |
} | |
} | |
} |
Author
robmccoll
commented
Jan 25, 2019
$go test -benchmem -bench .
goos: darwin
goarch: amd64
Benchmark0GoRoutineWG-8 50000000 22.9 ns/op 16 B/op 1 allocs/op
Benchmark1GoRoutineWG-8 3000000 539 ns/op 16 B/op 1 allocs/op
Benchmark10GoRoutineWG-8 500000 3431 ns/op 16 B/op 1 allocs/op
Benchmark100GoRoutineWG-8 50000 31071 ns/op 16 B/op 1 allocs/op
Benchmark1GoRoutineCh-8 3000000 493 ns/op 96 B/op 1 allocs/op
Benchmark10GoRoutineCh-8 200000 9723 ns/op 96 B/op 1 allocs/op
Benchmark100GoRoutineCh-8 20000 61699 ns/op 96 B/op 1 allocs/op
PASS
ok _/Users/rob 12.912s
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment