github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/bench/microbenchmarks/syncmap/compare_test.go (about)

     1  // Package memsys_test contains the corresponding micro-benchmarks.
     2  /*
     3   * Copyright (c) 2023-2024, NVIDIA CORPORATION. All rights reserved.
     4   */
     5  package syncmap_test
     6  
     7  import (
     8  	"sync"
     9  	"testing"
    10  
    11  	"github.com/NVIDIA/aistore/cmn/mono"
    12  )
    13  
    14  // $ go test -bench=. -benchmem
    15  // $ go test -bench=. -benchtime=10s -benchmem
    16  
    17  const mapSize = 16 // power of 2
    18  
    19  func BenchmarkSyncMap(b *testing.B) {
    20  	var m sync.Map
    21  	for i := range mapSize {
    22  		m.Store(i, new(int64))
    23  	}
    24  
    25  	b.RunParallel(func(pb *testing.PB) {
    26  		for pb.Next() {
    27  			j := int(mono.NanoTime() & (mapSize - 1)) // = mapSize -1
    28  			for i := j; i < j+mapSize; i++ {
    29  				v, ok := m.Load(i)
    30  				if ok {
    31  					val := v.(*int64)
    32  					*val++
    33  				}
    34  			}
    35  		}
    36  	})
    37  }
    38  
    39  func BenchmarkRegMap(b *testing.B) {
    40  	m := make(map[int]*int64, mapSize)
    41  	for i := range mapSize {
    42  		m[i] = new(int64)
    43  	}
    44  	lock := &sync.RWMutex{}
    45  
    46  	b.RunParallel(func(pb *testing.PB) {
    47  		for pb.Next() {
    48  			j := int(mono.NanoTime() & (mapSize - 1)) // = mapSize -1
    49  			for i := j; i < j+mapSize; i++ {
    50  				lock.RLock()
    51  				val, ok := m[i]
    52  				lock.RUnlock()
    53  				if ok {
    54  					*val++
    55  				}
    56  			}
    57  		}
    58  	})
    59  }