Last active
July 30, 2023 19:31
-
-
Save BitOfUniverse/12c8182ff349c1ccecf43e66986662dc to your computer and use it in GitHub Desktop.
Go routines performance test
This file contains hidden or 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 ( | |
"fmt" | |
"runtime" | |
"sync" | |
"time" | |
) | |
type Job struct { | |
} | |
func main() { | |
println("Hello, 世界") | |
jobs := make([]*Job, 3_000_000) | |
perfomanceTestWithLimitedWorkers(jobs) | |
perfomanceTestWithUnlimtedWorkers(jobs) | |
} | |
func perfomanceTestWithLimitedWorkers(jobs []*Job) { | |
var wg sync.WaitGroup | |
jobsCh := make(chan *Job, 1000) | |
maxConcurreny := runtime.NumCPU() | |
start := time.Now() | |
// Create worker goroutines | |
for i := 0; i < maxConcurreny; i++ { | |
wg.Add(1) | |
go batchWorker(&wg, jobsCh) | |
} | |
// Add jobs to the channel | |
for _, job := range jobs { | |
jobsCh <- job | |
} | |
close(jobsCh) | |
wg.Wait() | |
fmt.Printf("Took %s for %d jobs with %d (CPU cores) go routines\n", time.Since(start), len(jobs), maxConcurreny) | |
} | |
func perfomanceTestWithUnlimtedWorkers(jobs []*Job) { | |
var wg sync.WaitGroup | |
start := time.Now() | |
// Add jobs to the channel | |
for _, job := range jobs { | |
wg.Add(1) | |
go singleWorker(&wg, job) | |
} | |
wg.Wait() | |
fmt.Printf("Took %s for %d jobs with unlimited go routines\n", time.Since(start), len(jobs)) | |
} | |
func batchWorker(wg *sync.WaitGroup, jobs <-chan *Job) { | |
defer wg.Done() | |
for job := range jobs { | |
processJob(job) | |
} | |
} | |
func singleWorker(wg *sync.WaitGroup, job *Job) { | |
defer wg.Done() | |
processJob(job) | |
} | |
func processJob(job *Job) { | |
// Do some useless heavy CPU-bound work | |
for i := 0; i < 10_000; i++ { | |
_ = i * i | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment