Skip to content

Instantly share code, notes, and snippets.

@yardenlaif
Created June 15, 2023 11:12
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 yardenlaif/d4f8efce5f5dbe3105a23674b585e9ee to your computer and use it in GitHub Desktop.
Save yardenlaif/d4f8efce5f5dbe3105a23674b585e9ee to your computer and use it in GitHub Desktop.
package main
import (
"crypto/sha1"
"fmt"
"sync"
"testing"
)
var cases = []struct {
runCount int
}{
{runCount: 100},
{runCount: 1000},
{runCount: 10000},
{runCount: 100000},
{runCount: 1000000},
}
func task() {
sha1.Sum([]byte("hello world"))
}
func testChannel(runCount int) {
doneChan := make(chan struct{}, runCount)
// Execute tasks
for i := 0; i < runCount; i++ {
go func() {
defer func() { doneChan <- struct{}{} }()
task()
}()
}
// Wait for all tasks to complete
for i := 0; i < runCount; i++ {
<-doneChan
}
}
func BenchmarkChannel(b *testing.B) {
for _, c := range cases {
b.Run(fmt.Sprintf("runCount%d", c.runCount), func(b *testing.B) {
for i := 0; i < b.N; i++ {
testChannel(c.runCount)
}
})
}
}
func testWaitGroup(runCount int) {
wg := sync.WaitGroup{}
wg.Add(runCount)
// Execute tasks
for i := 0; i < runCount; i++ {
go func() {
defer wg.Done()
task()
}()
}
// Wait for all tasks to complete
wg.Wait()
}
func BenchmarkWaitGroup(b *testing.B) {
for _, c := range cases {
b.Run(fmt.Sprintf("runCount%d", c.runCount), func(b *testing.B) {
for i := 0; i < b.N; i++ {
testWaitGroup(c.runCount)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment