Skip to content

Instantly share code, notes, and snippets.

@siddontang
Created October 22, 2018 08:26
Show Gist options
  • Save siddontang/ee4cee6115b9d8d16286543c734f04d4 to your computer and use it in GitHub Desktop.
Save siddontang/ee4cee6115b9d8d16286543c734f04d4 to your computer and use it in GitHub Desktop.
package main
import (
"sync"
"sync/atomic"
"testing"
)
func main() {
// Parallel benchmark for text/template.Template.Execute on a single object.
r := testing.Benchmark(func(b *testing.B) {
var (
m sync.Mutex
level int
res int
)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
m.Lock()
res = level
m.Unlock()
}
})
})
println("use lock", r.String())
r = testing.Benchmark(func(b *testing.B) {
var (
level int32
res int32
)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
res = atomic.LoadInt32(&level)
}
})
})
println("use atomic", r.String())
}
@siddontang
Copy link
Author

use lock 50000000	        26.3 ns/op
use atomic 300000000	         4.36 ns/op

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