Skip to content

Instantly share code, notes, and snippets.

@mmirolim
Last active October 27, 2015 07:00
Show Gist options
  • Save mmirolim/6494fe234c03a6743743 to your computer and use it in GitHub Desktop.
Save mmirolim/6494fe234c03a6743743 to your computer and use it in GitHub Desktop.
to run or not to run goroutine
package pool
import (
"os"
"sync"
"sync/atomic"
"testing"
"time"
)
var (
jobDuration = 10 * time.Millisecond
maxJobLimit = 10000
jobNumber int64 = 0
job = make(chan struct{}, maxJobLimit)
done = make(chan struct{}, maxJobLimit)
)
func TestMain(m *testing.M) {
// start pool of goroutines
gopool(maxJobLimit, job, done)
os.Exit(m.Run())
}
func BenchmarkGoroutineCreation(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
go func(n int) {
if n < 0 {
return
}
}(i)
}
}
func BenchmarkNoGoroutineCreation(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
func(n int) {
if n < 0 {
return
}
}(i)
}
}
func BenchmarkConcurOp(b *testing.B) {
var wg sync.WaitGroup
b.ReportAllocs()
for i := 0; i < b.N; i++ {
wg.Add(1)
go func() {
time.Sleep(jobDuration)
wg.Done()
}()
}
wg.Wait()
}
func BenchmarkSeqOp(b *testing.B) {
f := func() {
time.Sleep(jobDuration)
}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
f()
}
}
func BenchmarkConcurOpInPool(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
job <- struct{}{}
// log.Println("job started", i)
atomic.AddInt64(&jobNumber, 1)
if atomic.LoadInt64(&jobNumber) > int64(maxJobLimit-2) {
select {
case <-done:
atomic.AddInt64(&jobNumber, -1)
}
}
}
}
func gopool(n int, job, done chan struct{}) {
for i := 0; i < n; i++ {
go func() {
for {
select {
case <-job:
time.Sleep(jobDuration)
done <- struct{}{}
break
}
}
}()
}
}
/*
PASS
BenchmarkGoroutineCreation-4 5000000 510 ns/op 0 B/op 0 allocs/op
BenchmarkNoGoroutineCreation-4 2000000000 2.14 ns/op 0 B/op 0 allocs/op
BenchmarkConcurOp-4 1000000 2913 ns/op 250 B/op 1 allocs/op
BenchmarkSeqOp-4 300 10096241 ns/op 64 B/op 1 allocs/op
BenchmarkConcurOpInPool-4 2000000 1288 ns/op 64 B/op 1 allocs/op
ok tests/goroutines 19.651s
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment