Created
June 15, 2023 11:12
-
-
Save yardenlaif/d4f8efce5f5dbe3105a23674b585e9ee to your computer and use it in GitHub Desktop.
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
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