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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment