LoginSignup
3
2

More than 5 years have passed since last update.

mutexとatomic比較

Last updated at Posted at 2017-06-15

ベンチマーク

package atomic_test

import (
    "sync"
    "sync/atomic"
    "testing"
)

func BenchmarkAtomic(b *testing.B) {
    var c uint32 = 0

    for i := 0; i < b.N; i++ {
        atomic.AddUint32(&c, 1)
        atomic.LoadUint32(&c)
    }
}

func BenchmarkMutex(b *testing.B) {
    var c uint32 = 0
    mutex := sync.RWMutex{}

    for i := 0; i < b.N; i++ {
        mutex.Lock()
        c++
        mutex.Unlock()

        mutex.RLock()
        _ = c
        mutex.RUnlock()
    }
}

結果

$ go test -run NONE -bench . -benchmem
testing: warning: no tests to run
BenchmarkAtomic-4       100000000           14.0 ns/op         0 B/op          0 allocs/op
BenchmarkMutex-4        20000000            60.7 ns/op         0 B/op          0 allocs/op
PASS
ok      none/goexp/atomic   2.729s
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2