Skip to content

Instantly share code, notes, and snippets.

@cyfdecyf
Last active July 5, 2023 16:40
Show Gist options
  • Save cyfdecyf/4562635 to your computer and use it in GitHub Desktop.
Save cyfdecyf/4562635 to your computer and use it in GitHub Desktop.
Performance test: mutex vs. channel in Go
// run with go test -test.bench Bench
package main
import (
// "fmt"
"runtime"
"sync"
"sync/atomic"
"testing"
)
const nProcuder = 4 // better to set this to core number
const nItem = 2000000
const totalItem = nProcuder * nItem
var data = [totalItem]byte{}
func init() {
runtime.GOMAXPROCS(nProcuder)
}
// channel version
//var channel = make(chan byte, nProcuder)
var channel = make(chan byte, totalItem)
func produce() {
for i := 0; i < nItem; i++ {
channel <- 1
}
}
func consume() {
for i := 0; i < nItem; i++ {
data[i] = <-channel
}
}
func testChannel() {
//fmt.Println("start test chan,", nProcuder, "producer")
for i := 0; i < nProcuder; i++ {
go produce()
}
consume()
}
func BenchmarkChan(b *testing.B) {
for i := 0; i < b.N; i++ {
testChannel()
}
}
// lock version
var mutex sync.Mutex
var id int
var wait int32
func addData(wg *sync.WaitGroup) {
atomic.AddInt32(&wait, 1)
for wait != nProcuder {
// wait all go routine start doing actual work
}
for i := 0; i < nItem; i++ {
mutex.Lock()
data[id] = 1
id++
mutex.Unlock()
}
wg.Done()
}
func testLock() {
wait = 0
id = 0
var wg sync.WaitGroup
wg.Add(nProcuder)
//fmt.Println("start test lock,", nProcuder, "producer")
for i := 0; i < nProcuder; i++ {
go addData(&wg)
}
wg.Wait()
}
func BenchmarkLock(b *testing.B) {
for i := 0; i < b.N; i++ {
testLock()
}
}
@wojtess
Copy link

wojtess commented Oct 16, 2021

what is results?

@NaurisSadovskis
Copy link

goos: darwin
goarch: arm64
pkg: hello/b
BenchmarkChan-4   	       7	 214774738 ns/op
BenchmarkLock-4   	       2	 980004188 ns/op
PASS
ok  	hello/b	6.451s

@smjure
Copy link

smjure commented Nov 15, 2022

Go 1.19.3

goos: linux
goarch: amd64
pkg: bnc
cpu: Intel(R) Core(TM) i9-9900KF CPU @ 3.60GHz
BenchmarkChan-4                    97               208299922 ns/op
BenchmarkLock-4                    54               221266225 ns/op
PASS
ok      bnc     38.170s

@wikiwang1991
Copy link

wikiwang1991 commented May 30, 2023

goos: linux
goarch: amd64
pkg: b
cpu: AMD Ryzen 7 5800H with Radeon Graphics         
BenchmarkChan-4               13          79569726 ns/op
BenchmarkLock-4                8         140473158 ns/op
PASS

go1.20.3

@wcf-ftnt
Copy link

wcf-ftnt commented Jul 5, 2023

It's not fair

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment