Skip to content

Instantly share code, notes, and snippets.

@okzk
Last active August 24, 2016 15:33
Show Gist options
  • Save okzk/e61bca866558934341557995e833e273 to your computer and use it in GitHub Desktop.
Save okzk/e61bca866558934341557995e833e273 to your computer and use it in GitHub Desktop.
package main
import (
"sync"
"testing"
"time"
)
const concurrency = 4
func BenchmarkLimitByWorkers(b *testing.B) {
ch := make(chan struct{}, 10000)
wg := sync.WaitGroup{}
wg.Add(concurrency)
for i := 0; i < concurrency; i++ {
go func() {
for range ch {
// 何かしら処理の代わり
// ベンチマークそのものに支配的にならないようにマイクロ秒だけsleep
time.Sleep(time.Microsecond)
}
wg.Done()
}()
}
for i := 0; i < b.N; i++ {
ch <- struct{}{}
}
close(ch)
wg.Wait()
}
func BenchmarkLimitBySemaphore(b *testing.B) {
ch := make(chan struct{}, concurrency)
wg := sync.WaitGroup{}
wg.Add(b.N)
for i := 0; i < b.N; i++ {
go func() {
ch <- struct{}{}
// 何かしら処理の代わり
// ベンチマークそのものに支配的にならないようにマイクロ秒だけsleep
time.Sleep(time.Microsecond)
<-ch
wg.Done()
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment