-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a very crude comparative benchmark.
Roughly compare the performance of accumulating values with a separate goroutine via a channel, vs. accumulating them directly under a lock.
- Loading branch information
1 parent
ad5bfc7
commit 9a6c1f5
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package taskgroup_test | ||
|
||
import ( | ||
"math/rand" | ||
"sync" | ||
"testing" | ||
) | ||
|
||
// A very rough benchmark comparing the performance of accumulating values with | ||
// a separate goroutine via a channel, vs. accumulating them directly under a | ||
// lock. The workload here is intentionally minimal, so the benchmark is | ||
// measuring more or less just the overhead. | ||
|
||
func BenchmarkChan(b *testing.B) { | ||
ch := make(chan int) | ||
done := make(chan struct{}) | ||
var total int | ||
go func() { | ||
defer close(done) | ||
for v := range ch { | ||
total += v | ||
} | ||
}() | ||
b.ResetTimer() // discount the setup time. | ||
|
||
var wg sync.WaitGroup | ||
wg.Add(b.N) | ||
for i := 0; i < b.N; i++ { | ||
go func() { | ||
defer wg.Done() | ||
ch <- rand.Intn(1000) | ||
}() | ||
} | ||
wg.Wait() | ||
close(ch) | ||
<-done | ||
} | ||
|
||
func BenchmarkLock(b *testing.B) { | ||
var μ sync.Mutex | ||
var total int | ||
report := func(v int) { | ||
μ.Lock() | ||
defer μ.Unlock() | ||
total += v | ||
} | ||
b.ResetTimer() // discount the setup time. | ||
|
||
var wg sync.WaitGroup | ||
wg.Add(b.N) | ||
for i := 0; i < b.N; i++ { | ||
go func() { | ||
defer wg.Done() | ||
report(rand.Intn(1000)) | ||
}() | ||
} | ||
wg.Wait() | ||
} |