Last active
January 19, 2020 08:17
-
-
Save YooWaan/4fec0d47e22334b29bfd42aefcc99d8d to your computer and use it in GitHub Desktop.
golang atomic, mutext bench
This file contains 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 ( | |
"sync" | |
"sync/atomic" | |
) | |
var mutex sync.Mutex | |
var value atomic.Value | |
type Counter int64 | |
func (c *Counter) Inc() { | |
*c++ | |
} | |
func (c *Counter) AtomicInc() { | |
atomic.AddInt64((*int64)(c), 1) | |
} | |
func (c *Counter) LockInc() { | |
mutex.Lock() | |
defer mutex.Unlock() | |
*c++ | |
} | |
func incValue() { | |
cnt := value.Load().(Counter) | |
cnt++ | |
value.Store(cnt) | |
} | |
func countup(inc func(), n int) { | |
var wg sync.WaitGroup | |
for i := 0; i < n; i++ { | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
inc() | |
}() | |
} | |
wg.Wait() | |
} |
This file contains 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 | |
// go test -bench . | grep 'ns/op' | |
import ( | |
"testing" | |
) | |
func BenchmarkInc_Countup(b *testing.B) { | |
var cnt Counter | |
b.ResetTimer() | |
countup(cnt.Inc, b.N) | |
b.Logf("%d -> %d", b.N, cnt) | |
} | |
func BenchmarkLock_Countup(b *testing.B) { | |
var cnt Counter | |
b.ResetTimer() | |
countup(cnt.LockInc, b.N) | |
b.Logf("%d -> %d", b.N, cnt) | |
} | |
func BenchmarkAtomic_Countup(b *testing.B) { | |
var cnt Counter | |
b.ResetTimer() | |
countup(cnt.AtomicInc, b.N) | |
b.Logf("%d -> %d", b.N, cnt) | |
} | |
func BenchmarkAtomicValue_Countup(b *testing.B) { | |
var cnt Counter | |
value.Store(cnt) | |
b.ResetTimer() | |
countup(incValue, b.N) | |
cnt = value.Load().(Counter) | |
b.Logf("%d -> %d", b.N, cnt) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment