github.com/bruceshao/lockfree@v1.1.3-0.20230816090528-e89824c0a6e9/cursor_test.go (about) 1 /* 2 * Copyright (C) THL A29 Limited, a Tencent company. All rights reserved. 3 * 4 * SPDX-License-Identifier: Apache-2.0 5 * 6 */ 7 8 package lockfree 9 10 import ( 11 "fmt" 12 "sync" 13 "sync/atomic" 14 "testing" 15 "time" 16 ) 17 18 func TestCursor(t *testing.T) { 19 c := newCursor() 20 ts := time.Now() 21 for i := 0; i < 100000000; i++ { 22 x := c.increment() 23 if x%1000000 == 0 { 24 fmt.Println(x) 25 } 26 } 27 tl := time.Since(ts) 28 fmt.Printf("time = %v\n", tl) 29 } 30 31 func TestCursor2(t *testing.T) { 32 c := newCursor() 33 var wg sync.WaitGroup 34 wg.Add(10000) 35 ts := time.Now() 36 for i := 0; i < 10000; i++ { 37 go func() { 38 for j := 0; j < 10000; j++ { 39 x := c.increment() 40 if x%10000000 == 0 { 41 fmt.Println(x) 42 } 43 } 44 wg.Done() 45 }() 46 } 47 wg.Wait() 48 fmt.Println(time.Since(ts)) 49 } 50 51 func TestCursor3(t *testing.T) { 52 var c uint64 53 var wg sync.WaitGroup 54 wg.Add(10000) 55 ts := time.Now() 56 for i := 0; i < 10000; i++ { 57 go func() { 58 for j := 0; j < 10000; j++ { 59 x := atomic.AddUint64(&c, 1) 60 if x%10000000 == 0 { 61 fmt.Println(x) 62 } 63 } 64 wg.Done() 65 }() 66 } 67 wg.Wait() 68 fmt.Println(time.Since(ts)) 69 } 70 71 type NoPad struct { 72 a uint64 73 b uint64 74 c uint64 75 } 76 77 func (np *NoPad) Increase() { 78 atomic.AddUint64(&np.a, 1) 79 atomic.AddUint64(&np.b, 1) 80 atomic.AddUint64(&np.c, 1) 81 } 82 83 type Pad struct { 84 a uint64 85 _p1 [8]uint64 86 b uint64 87 _p2 [8]uint64 88 c uint64 89 _p3 [8]uint64 90 } 91 92 func (p *Pad) Increase() { 93 atomic.AddUint64(&p.a, 1) 94 atomic.AddUint64(&p.b, 1) 95 atomic.AddUint64(&p.c, 1) 96 } 97 98 func BenchmarkPad_Increase(b *testing.B) { 99 pad := &Pad{} 100 b.RunParallel(func(pb *testing.PB) { 101 for pb.Next() { 102 pad.Increase() 103 } 104 }) 105 } 106 func BenchmarkNoPad_Increase(b *testing.B) { 107 nopad := &NoPad{} 108 b.RunParallel(func(pb *testing.PB) { 109 for pb.Next() { 110 nopad.Increase() 111 } 112 }) 113 }