Debian Codegraph @

pdata/pprofile/stacks_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package pprofile
5
6 import (
7 "testing"
8
9 "github.com/stretchr/testify/assert"
10 "github.com/stretchr/testify/require"
11
12 "go.opentelemetry.io/collector/internal/testutil"
13 )
14
15 func TestSetStack(t *testing.T) {
16 table := NewStackSlice()
17 s := NewStack()
18 s.LocationIndices().Append(1)
19 s2 := NewStack()
20 s.LocationIndices().Append(2)
21
22 // Put a first stack
23 idx, err := SetStack(table, s)
24 require.NoError(t, err)
25 assert.Equal(t, 1, table.Len())
26 assert.Equal(t, int32(0), idx)
27
28 // Put the same stack
29 // This should be a no-op.
30 idx, err = SetStack(table, s)
31 require.NoError(t, err)
32 assert.Equal(t, 1, table.Len())
33 assert.Equal(t, int32(0), idx)
34
35 // Set a new stack
36 // This sets the index and adds to the table.
37 idx, err = SetStack(table, s2)
38 require.NoError(t, err)
39 assert.Equal(t, 2, table.Len())
40 assert.Equal(t, int32(table.Len()-1), idx)
41
42 // Set an existing stack
43 idx, err = SetStack(table, s)
44 require.NoError(t, err)
45 assert.Equal(t, 2, table.Len())
46 assert.Equal(t, int32(0), idx)
47 // Set another existing stack
48 idx, err = SetStack(table, s2)
49 require.NoError(t, err)
50 assert.Equal(t, 2, table.Len())
51 assert.Equal(t, int32(table.Len()-1), idx)
52 }
53
54 func BenchmarkSetStack(b *testing.B) {
55 testutil.SkipMemoryBench(b)
56 for _, bb := range []struct {
57 name string
58 stack Stack
59
60 runBefore func(*testing.B, StackSlice)
61 }{
62 {
63 name: "with a new stack",
64 stack: NewStack(),
65 },
66 {
67 name: "with an existing stack",
68 stack: func() Stack {
69 s := NewStack()
70 s.LocationIndices().Append(1)
71 return s
72 }(),
73
74 runBefore: func(_ *testing.B, table StackSlice) {
75 s := table.AppendEmpty()
76 s.LocationIndices().Append(1)
77 },
78 },
79 {
80 name: "with a duplicate stack",
81 stack: NewStack(),
82
83 runBefore: func(_ *testing.B, table StackSlice) {
84 _, err := SetStack(table, NewStack())
85 require.NoError(b, err)
86 },
87 },
88 {
89 name: "with a hundred stacks to loop through",
90 stack: func() Stack {
91 s := NewStack()
92 s.LocationIndices().Append(1)
93 return s
94 }(),
95
96 runBefore: func(_ *testing.B, table StackSlice) {
97 for range 100 {
98 table.AppendEmpty()
99 }
100 },
101 },
102 } {
103 b.Run(bb.name, func(b *testing.B) {
104 table := NewStackSlice()
105
106 if bb.runBefore != nil {
107 bb.runBefore(b, table)
108 }
109
110 b.ResetTimer()
111 b.ReportAllocs()
112
113 for b.Loop() {
114 _, _ = SetStack(table, bb.stack)
115 }
116 })
117 }
118 }