Skip to content

Instantly share code, notes, and snippets.

@devlights
Last active May 4, 2025 05:12
Show Gist options
  • Select an option

  • Save devlights/5b2b950736b660f3e12d3d08629e7384 to your computer and use it in GitHub Desktop.

Select an option

Save devlights/5b2b950736b660f3e12d3d08629e7384 to your computer and use it in GitHub Desktop.
[Go] channel buffering speed compare
package main
import (
"flag"
"fmt"
"io"
"runtime"
"sync"
)
func main() {
var (
loopcnt = flag.Int("loop", 10000, "loop count")
incnt = flag.Int("inch", 0, "input ch buffer count, 0 is unbuffered")
outcnt = flag.Int("outch", 0, "output ch buffer count, 0 is unbuffered")
)
flag.Parse()
var (
wg sync.WaitGroup
numWorkers = runtime.GOMAXPROCS(0)
in = make(chan int, *incnt)
out = make(chan string, *outcnt)
)
go func() {
defer close(in)
for i := range *loopcnt {
in <- i
}
}()
fmt.Printf("numWorkers=%d\n", numWorkers)
wg.Add(numWorkers)
for i := range numWorkers {
go func(id int) {
defer wg.Done()
for j := range in {
out <- fmt.Sprintf("[%d] hello world [%d]", id, j)
}
}(i + 1)
}
go func() {
wg.Wait()
close(out)
}()
for v := range out {
fmt.Fprintln(io.Discard, v)
}
fmt.Println("done")
}
$ task
task: [default] goimports -w main.go
task: [default] go build -o app main.go
task: [default] time ./app -loop 3000000 -inch 0 -outch 0
numWorkers=8
done

real    0m7.995s
user    0m0.000s
sys     0m0.000s
task: [default] time ./app -loop 3000000 -inch 3000000 -outch 0
numWorkers=8
done

real    0m6.710s
user    0m0.000s
sys     0m0.000s
task: [default] time ./app -loop 3000000 -inch 3000000 -outch 3000000
numWorkers=8
done

real    0m2.311s
user    0m0.000s
sys     0m0.000s
# https://taskfile.dev
version: '3'
vars:
LOOP_CNT: 3000000
ZERO: 0
tasks:
default:
cmds:
- goimports -w main.go
- go build -o app main.go
- time ./app -loop {{.LOOP_CNT}} -inch {{.ZERO}} -outch {{.ZERO}}
- time ./app -loop {{.LOOP_CNT}} -inch {{.LOOP_CNT}} -outch {{.ZERO}}
- time ./app -loop {{.LOOP_CNT}} -inch {{.LOOP_CNT}} -outch {{.LOOP_CNT}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment