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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| package main
import ( "fmt" "sync" "time" )
type rwMap struct { data map[int]int m sync.RWMutex }
var ( rwm = rwMap{data: make(map[int]int)} end = int(1e7) syncM sync.Map )
func main() {
fmt.Println("write test") // rw map start := time.Now() for i := 0; i < end; i++ { rwm.m.Lock() rwm.data[i] = i rwm.m.Unlock() } fmt.Printf("rw map used %v\n", time.Since(start))
// sync Map start = time.Now() for i := 0; i < end; i++ { syncM.Store(i, i) } fmt.Printf("sync map used %v\n\n", time.Since(start))
fmt.Println("read test") // rw map start = time.Now() for i := 0; i < end; i++ { rwm.m.RLock() _ = rwm.data[i] rwm.m.RUnlock() } fmt.Printf("rw map used %v\n", time.Since(start))
// sync Map start = time.Now() for i := 0; i < end; i++ { _, _ = syncM.Load(i) } fmt.Printf("sync map used %v\n\n", time.Since(start))
}
|