Skip to content

Instantly share code, notes, and snippets.

@zabawaba99
Created August 31, 2015 14:20
Show Gist options
  • Save zabawaba99/7d9193ff0752186ad6e6 to your computer and use it in GitHub Desktop.
Save zabawaba99/7d9193ff0752186ad6e6 to your computer and use it in GitHub Desktop.
Benchmarking new go routine vs pool
package wrkpool
import (
"sync"
"testing"
)
const RunCount = 10000
func BenchmarkTestNewRoutine(b *testing.B) {
for i := 0; i < b.N; i++ {
var wg sync.WaitGroup
for j := 0; j < RunCount; j++ {
wg.Add(1)
go func() {
SomeJob()
wg.Done()
}()
}
wg.Wait()
}
}
func BenchmarkTestPool(b *testing.B) {
for i := 0; i < b.N; i++ {
var wg sync.WaitGroup
pool := make(chan struct{}, 25)
// fill up the pool
for i := 0; i < 25; i++ {
pool <- struct{}{}
}
for j := 0; j < RunCount; j++ {
<-pool
wg.Add(1)
go func() {
SomeJob()
pool <- struct{}{}
wg.Done()
}()
}
wg.Wait()
}
}
func SomeJob() int {
var result int
for i := 0; i < 10000; i++ {
result += i
}
return result
}
@zabawaba99
Copy link
Author

RunCount at 1000

$ go test -bench . -benchmem
testing: warning: no tests to run
PASS
BenchmarkTestNewRoutine-8       2000        912813 ns/op          30 B/op          1 allocs/op
BenchmarkTestPool-8             2000        945420 ns/op         112 B/op          2 allocs/op
ok      github.com/zabawaba99/wrkpool   3.915s
$ go test -bench . -benchmem -benchtime 30s
testing: warning: no tests to run
PASS
BenchmarkTestNewRoutine-8      50000        924478 ns/op          16 B/op          1 allocs/op
BenchmarkTestPool-8            50000        976914 ns/op         112 B/op          2 allocs/op
ok      github.com/zabawaba99/wrkpool   113.978s

RunCount at 10000

$ go test -bench . -benchmem
testing: warning: no tests to run
PASS
BenchmarkTestNewRoutine-8        200       8829387 ns/op        3253 B/op          8 allocs/op
BenchmarkTestPool-8              200       9323445 ns/op         112 B/op          2 allocs/op
ok      github.com/zabawaba99/wrkpool   5.483s
$ go test -bench . -benchmem -benchtime 30s
testing: warning: no tests to run
PASS
BenchmarkTestNewRoutine-8       5000       8819895 ns/op          27 B/op          1 allocs/op
BenchmarkTestPool-8             5000       9365598 ns/op         112 B/op          2 allocs/op
ok      github.com/zabawaba99/wrkpool   92.814s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment