Created
November 10, 2024 13:08
-
-
Save veggiemonk/0b2cc987a4d5914b3885bbaad0340601 to your computer and use it in GitHub Desktop.
quick benchmark for atomic
This file contains hidden or 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" | |
"testing" | |
) | |
type atom struct { | |
value atomic.Int64 | |
} | |
type mute struct { | |
value int64 | |
lock sync.Mutex | |
} | |
var ( | |
a = atom{} | |
m = mute{} | |
) | |
var ( | |
resa int64 = 0 | |
resm int64 = 0 | |
) | |
func BenchmarkAtomicWrite(b *testing.B) { | |
b.RunParallel(func(pb *testing.PB) { | |
for pb.Next() { | |
a.value.Add(1) | |
} | |
}) | |
} | |
func BenchmarkMutexWrite(b *testing.B) { | |
b.RunParallel(func(pb *testing.PB) { | |
for pb.Next() { | |
m.lock.Lock() | |
m.value++ | |
m.lock.Unlock() | |
} | |
}) | |
} | |
func BenchmarkAtomicRead(b *testing.B) { | |
b.RunParallel(func(pb *testing.PB) { | |
var r int64 | |
for pb.Next() { | |
r = a.value.Load() | |
} | |
resa = r | |
}) | |
} | |
func BenchmarkMutexRead(b *testing.B) { | |
b.RunParallel(func(pb *testing.PB) { | |
var r int64 | |
for pb.Next() { | |
m.lock.Lock() | |
r = m.value | |
m.lock.Unlock() | |
} | |
resm = r | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment