Skip to content

Instantly share code, notes, and snippets.

@linxGnu
Last active April 27, 2022 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linxGnu/4c0d2703cd154f8123fcd2250b7a4b32 to your computer and use it in GitHub Desktop.
Save linxGnu/4c0d2703cd154f8123fcd2250b7a4b32 to your computer and use it in GitHub Desktop.
package internal
import (
"sync"
"testing"
"time"
)
//goos: darwin
//goarch: amd64
//pkg: hello/internal
//cpu: Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
//BenchmarkSpawnInWild
//BenchmarkSpawnInWild-16 1 2477192780 ns/op 4712624 B/op 25819 allocs/op
//BenchmarkWorkerPool
//BenchmarkWorkerPool-16 1 2546894379 ns/op 257424 B/op 9022 allocs/op
const (
numComputeUnit = 32
rangeLimit = 10_000
concurrentCompute = 256
)
func BenchmarkSpawnInWild(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
var wg sync.WaitGroup
wg.Add(concurrentCompute)
for j := 0; j < concurrentCompute; j++ {
go func() {
computeWithWildRoutines()
wg.Done()
}()
}
wg.Wait()
}
}
func BenchmarkWorkerPool(b *testing.B) {
// start worker pool
taskCh := make(chan func(), 64)
for i := 0; i < 128; i++ {
go func() {
for task := range taskCh {
task() // execute task
}
}()
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
var wg sync.WaitGroup
wg.Add(concurrentCompute)
for j := 0; j < concurrentCompute; j++ {
go func() {
computeWithWorkerPool(taskCh)
wg.Done()
}()
}
wg.Wait()
}
close(taskCh)
}
func computeWithWildRoutines() {
out := make(chan int, numComputeUnit)
for i := 0; i < numComputeUnit; i++ {
go func() {
total := 0
for i := 1; i <= rangeLimit; i++ {
total += i%593 + (i*i)/913
time.Sleep(time.Microsecond)
}
out <- total
}()
}
sum := 0
for i := 0; i < numComputeUnit; i++ {
sum += <-out
}
if sum == 0 {
panic(sum)
}
}
func computeWithWorkerPool(taskCh chan func()) {
out := make(chan int, numComputeUnit)
for i := 0; i < numComputeUnit; i++ {
// give compute task to allocated workers
taskCh <- func() {
total := 0
for i := 1; i <= rangeLimit; i++ {
total += i%593 + (i*i)/913
time.Sleep(time.Microsecond)
}
out <- total
}
}
sum := 0
for i := 0; i < numComputeUnit; i++ {
sum += <-out
}
if sum == 0 {
panic(sum)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment