package main`
import (
"sync"
"testing"
"time"
)
const (
cost = 10 * time.Microsecond
)
type RW interface {
Write()
Read()
}
type Lock struct {
count int
mu sync.Mutex
}
func (l *Lock) Read() {
l.mu.Lock()
time.Sleep(cost)
_ = l.count
l.mu.Unlock()
}
func (l *Lock) Write() {
l.mu.Lock()
l.count++
time.Sleep(cost)
l.mu.Unlock()
}
type RWLock struct {
count int
mu sync.RWMutex
}
func (r *RWLock) Read() {
r.mu.Lock()
time.Sleep(cost)
_ = r.count
r.mu.Unlock()
}
func (r *RWLock) Write() {
r.mu.Lock()
r.count++
time.Sleep(cost)
r.mu.Unlock()
}
func benchmark(b *testing.B, rw RW, read, write int) {
for i := 0; i < b.N; i++ {
var wg sync.WaitGroup
for k := 0; k < read*100; k++ {
wg.Add(1)
go func() {
rw.Read()
wg.Done()
}()
}
for m := 0; m < write*100; m++ {
wg.Add(1)
go func() {
rw.Write()
wg.Done()
}()
}
wg.Wait()
}
}
func BenchmarkReadMore(b *testing.B) {
benchmark(b, &Lock{}, 9, 1)
}
func BenchmarkReadMoreRW(b *testing.B) {
benchmark(b, &RWLock{}, 9, 1)
}
func BenchmarkWriteMore(b *testing.B) {
benchmark(b, &Lock{}, 1, 9)
}
func BenchmarkWriteMoreRW(b *testing.B) {
benchmark(b, &RWLock{}, 1, 9)
}
func BenchmarkReadEqual(b *testing.B) {
benchmark(b, &Lock{}, 5, 5)
}
func BenchmarkReadEqualRW(b *testing.B) {
benchmark(b, &RWLock{}, 5, 5)
}
下面这是我的执行结果:
goarch: amd64
pkg: test
cpu: Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
|BenchmarkReadMore-8| 62| 18909825| ns/op|
|BenchmarkReadMoreRW-8 | 63| 18825713 |ns/op |
|BenchmarkWriteMore-8 | 63 | 18774136| ns/op |
|BenchmarkWriteMoreRW-8 | 63 | 20889956 ns/op |
PASS
ok test 5.407s
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.