golang[85]-测试读锁的性能

测试读锁的性能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
"math/rand"
"sync"
"testing"
"time"
)



var m map[int]string
var lock sync.RWMutex
func init(){
rand.Seed(time.Now().Unix())
m:=make(map[int]string,100000)
for i:=0;i<100000;i++{
m[i] = "helloworld"
}
}
func Benchmark1(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = m[rand.Int()%100000]
}
}

func Benchmark2(b *testing.B) {
for i := 0; i < b.N; i++ {
lock.RLock()
_ = m[rand.Int()%100000]
lock.RUnlock()
}
}

bench

1
2
3
4
5
6
7
go test . -bench .
goos: darwin
goarch: amd64
pkg: gitlab.followme.com/CopyTradingGo/tools/GRPC_TEST/test3
Benchmark1-12 100000000 18.9 ns/op
Benchmark2-12 50000000 29.4 ns/op
PASS