golang made a mutex with atomic performance test

func BenchmarkMutex(b *testing.B)  {
    var number int
    lock := sync.Mutex{}
    for i:=0; i< b.N;i++{
        go func() {
            defer lock.Unlock()
            lock.Lock()
            number++
        }()
    }
}

func BenchmarkAtomic(b *testing.B)  {
    var number int32
    for i:=0; i< b.N;i++{
        go func() {
            atomic.AddInt32(&number, 1)
        }()
    }
}

Performance tests benchmarkMutex and benchmarkAtomic two mutex function to compare differences

$ go test -v -cpu 1,2,4 -benchmem   -bench=. 
goos: darwin
goarch: amd64
pkg: puzzlers/article21/q3
BenchmarkMutex            1000000               2949 ns / at              424 W / in           0 ALLOCS / on
BenchmarkMutex - 2          5000000                336 ns / at               22 B / at           0 ALLOCS / in
BenchmarkMutex - 4         10000000                205 ns / at                0 B / at           0 ALLOCS / in
BenchmarkAtomic           2000000               1745 ns / at              156 B / on           0 allocs / on
BenchmarkAtomic - 2        10000000                176 ns / on                0 B / on           0 allocs / on
BenchmarkAtomic - 4        10000000                225 ns / on                0 B / on           0 allocs / on
PASS
ok      puzzlers/article21/q3   26.179s

We found that the performance of higher atomic lock mutex regardless of CPU and memory consumption than the mutex lock is better than running from

Guess you like

Origin www.cnblogs.com/jackey2015/p/11737570.html