github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/sets/zset/zset_bench_test.go (about) 1 package zset 2 3 import ( 4 "math" 5 "strconv" 6 "testing" 7 8 "github.com/songzhibin97/go-baseutils/base/bcomparator" 9 "github.com/songzhibin97/go-baseutils/sys/fastrand" 10 ) 11 12 const initSize = 1 << 10 13 14 const randN = math.MaxUint32 15 16 func BenchmarkContains100Hits(b *testing.B) { 17 benchmarkContainsNHits(b, 100) 18 } 19 20 func BenchmarkContains50Hits(b *testing.B) { 21 benchmarkContainsNHits(b, 50) 22 } 23 24 func BenchmarkContainsNoHits(b *testing.B) { 25 benchmarkContainsNHits(b, 0) 26 } 27 28 func benchmarkContainsNHits(b *testing.B, n int) { 29 b.Run("sortedset", func(b *testing.B) { 30 z := New[string](bcomparator.StringComparator()) 31 var vals []string 32 for i := 0; i < initSize; i++ { 33 val := strconv.Itoa(i) 34 vals = append(vals, val) 35 if fastrand.Intn(100)+1 <= n { 36 z.AddB(fastrand.Float64(), val) 37 } 38 } 39 b.ResetTimer() 40 b.RunParallel(func(pb *testing.PB) { 41 for pb.Next() { 42 _ = z.Contains(vals[fastrand.Intn(initSize)]) 43 } 44 }) 45 }) 46 } 47 48 func BenchmarkAdd(b *testing.B) { 49 benchmarkNAddNIncrNRemoveNContains(b, 100, 0, 0, 0) 50 } 51 52 func Benchmark1Add99Contains(b *testing.B) { 53 benchmarkNAddNIncrNRemoveNContains(b, 1, 0, 0, 99) 54 } 55 56 func Benchmark10Add90Contains(b *testing.B) { 57 benchmarkNAddNIncrNRemoveNContains(b, 10, 0, 0, 90) 58 } 59 60 func Benchmark50Add50Contains(b *testing.B) { 61 benchmarkNAddNIncrNRemoveNContains(b, 50, 0, 0, 50) 62 } 63 64 func Benchmark1Add3Incr6Remove90Contains(b *testing.B) { 65 benchmarkNAddNIncrNRemoveNContains(b, 1, 3, 6, 90) 66 } 67 68 func benchmarkNAddNIncrNRemoveNContains(b *testing.B, nAdd, nIncr, nRemove, nContains int) { 69 // var anAdd, anIncr, anRemove, anContains int 70 71 b.Run("sortedset", func(b *testing.B) { 72 z := New[string](bcomparator.StringComparator()) 73 var vals []string 74 var scores []float64 75 var ops []int 76 for i := 0; i < initSize; i++ { 77 vals = append(vals, strconv.Itoa(fastrand.Intn(randN))) 78 scores = append(scores, fastrand.Float64()) 79 ops = append(ops, fastrand.Intn(100)) 80 } 81 b.ResetTimer() 82 b.RunParallel(func(pb *testing.PB) { 83 for pb.Next() { 84 r := fastrand.Intn(initSize) 85 val := vals[r] 86 if u := ops[r] + 1; u <= nAdd { 87 // anAdd++ 88 z.AddB(scores[r], val) 89 } else if u-nAdd <= nIncr { 90 // anIncr++ 91 z.IncrBy(scores[r], val) 92 } else if u-nAdd-nIncr <= nRemove { 93 // anRemove++ 94 z.Remove(val) 95 } else if u-nAdd-nIncr-nRemove <= nContains { 96 // anContains++ 97 z.Contains(val) 98 } 99 } 100 }) 101 // b.Logf("N: %d, Add: %f, Incr: %f, Remove: %f, Contains: %f", b.N, float64(anAdd)/float64(b.N), float64(anIncr)/float64(b.N), float64(anRemove)/float64(b.N), float64(anContains)/float64(b.N)) 102 }) 103 }