Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/river/vm/vm_benchmarks_test.go
4095 views
1
package vm_test
2
3
import (
4
"reflect"
5
"testing"
6
7
"github.com/grafana/agent/pkg/river/parser"
8
"github.com/grafana/agent/pkg/river/vm"
9
"github.com/stretchr/testify/require"
10
)
11
12
func BenchmarkExprs(b *testing.B) {
13
// Shared scope across all tests below
14
scope := &vm.Scope{
15
Variables: map[string]interface{}{
16
"foobar": int(42),
17
},
18
}
19
20
tt := []struct {
21
name string
22
input string
23
expect interface{}
24
}{
25
// Binops
26
{"or", `false || true`, bool(true)},
27
{"and", `true && false`, bool(false)},
28
{"math/eq", `3 == 5`, bool(false)},
29
{"math/neq", `3 != 5`, bool(true)},
30
{"math/lt", `3 < 5`, bool(true)},
31
{"math/lte", `3 <= 5`, bool(true)},
32
{"math/gt", `3 > 5`, bool(false)},
33
{"math/gte", `3 >= 5`, bool(false)},
34
{"math/add", `3 + 5`, int(8)},
35
{"math/sub", `3 - 5`, int(-2)},
36
{"math/mul", `3 * 5`, int(15)},
37
{"math/div", `3 / 5`, int(0)},
38
{"math/mod", `5 % 3`, int(2)},
39
{"math/pow", `3 ^ 5`, int(243)},
40
{"binop chain", `3 + 5 * 2`, int(13)}, // Chain multiple binops
41
42
// Identifier
43
{"ident lookup", `foobar`, int(42)},
44
45
// Arrays
46
{"array", `[0, 1, 2]`, []int{0, 1, 2}},
47
48
// Objects
49
{"object to map", `{ a = 5, b = 10 }`, map[string]int{"a": 5, "b": 10}},
50
{
51
name: "object to struct",
52
input: `{
53
name = "John Doe",
54
age = 42,
55
}`,
56
expect: struct {
57
Name string `river:"name,attr"`
58
Age int `river:"age,attr"`
59
Country string `river:"country,attr,optional"`
60
}{
61
Name: "John Doe",
62
Age: 42,
63
},
64
},
65
66
// Access
67
{"access", `{ a = 15 }.a`, int(15)},
68
{"nested access", `{ a = { b = 12 } }.a.b`, int(12)},
69
70
// Indexing
71
{"index", `[0, 1, 2][1]`, int(1)},
72
{"nested index", `[[1,2,3]][0][2]`, int(3)},
73
74
// Paren
75
{"paren", `(15)`, int(15)},
76
77
// Unary
78
{"unary not", `!true`, bool(false)},
79
{"unary neg", `-15`, int(-15)},
80
}
81
82
for _, tc := range tt {
83
b.Run(tc.name, func(b *testing.B) {
84
b.StopTimer()
85
expr, err := parser.ParseExpression(tc.input)
86
require.NoError(b, err)
87
88
eval := vm.New(expr)
89
b.StartTimer()
90
91
expectType := reflect.TypeOf(tc.expect)
92
93
for i := 0; i < b.N; i++ {
94
vPtr := reflect.New(expectType).Interface()
95
_ = eval.Evaluate(scope, vPtr)
96
}
97
})
98
}
99
}
100
101