github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/16cacheline/padding_test.go (about)

     1  package cacheline
     2  
     3  import (
     4  	"sync/atomic"
     5  	"testing"
     6  )
     7  
     8  //https://colobu.com/2019/01/24/cacheline-affects-performance-in-go/
     9  
    10  /*
    11  可以使用intel-go/cpuid获取CPU的cacheline的大小
    12  https://github.com/intel-go/cpuid
    13  
    14  也提供了一个CacheLinePad struct用来padding 	cpu.CacheLinePad{}
    15  https://github.com/golang/sys/blob/master/cpu/cpu.go
    16  */
    17  
    18  type NoPad struct {
    19  	//_ cpu.CacheLinePad // 缓存行
    20  	a uint64
    21  	b uint64
    22  	c uint64
    23  }
    24  
    25  func (np *NoPad) Increase() {
    26  	atomic.AddUint64(&np.a, 1)
    27  	atomic.AddUint64(&np.b, 1)
    28  	atomic.AddUint64(&np.c, 1)
    29  }
    30  
    31  type Pad struct {
    32  	a   uint64
    33  	_p1 [8]uint64
    34  	b   uint64
    35  	_p2 [8]uint64
    36  	c   uint64
    37  	_p3 [8]uint64
    38  }
    39  
    40  func (p *Pad) Increase() {
    41  	atomic.AddUint64(&p.a, 1)
    42  	atomic.AddUint64(&p.b, 1)
    43  	atomic.AddUint64(&p.c, 1)
    44  }
    45  
    46  func BenchmarkPad_Increase(b *testing.B) {
    47  	pad := &Pad{}
    48  	b.RunParallel(func(pb *testing.PB) {
    49  		for pb.Next() {
    50  			pad.Increase()
    51  		}
    52  	})
    53  }
    54  
    55  func BenchmarkNoPad_Increase(b *testing.B) {
    56  	nopad := &NoPad{}
    57  	b.RunParallel(func(pb *testing.PB) {
    58  		for pb.Next() {
    59  			nopad.Increase()
    60  		}
    61  	})
    62  }