Skip to content

Commit f6e2d87

Browse files
committed
make the benchmarks more fair
1 parent 32aebcd commit f6e2d87

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

checker/checker_bench_test.go

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package checker_test
22

33
import (
4+
"runtime"
45
"testing"
56

67
"github.com/expr-lang/expr"
8+
"github.com/expr-lang/expr/ast"
79
"github.com/expr-lang/expr/checker"
10+
"github.com/expr-lang/expr/checker/nature"
811
"github.com/expr-lang/expr/conf"
912
"github.com/expr-lang/expr/parser"
1013
)
@@ -59,22 +62,51 @@ a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a
5962
expr.ConstExpr("func")
6063

6164
for _, c := range cases {
62-
b.Run("name="+c.name, func(b *testing.B) {
65+
batchSize := 100_000
66+
if batchSize > b.N {
67+
batchSize = b.N
68+
}
69+
trees := make([]*parser.Tree, 0, batchSize)
70+
for i := 0; i < batchSize; i++ {
6371
tree, err := parser.ParseWithConfig(c.input, config)
6472
if err != nil {
6573
b.Fatal(err)
6674
}
67-
b.ReportAllocs()
68-
b.ResetTimer()
75+
trees = append(trees, tree)
76+
}
77+
runtime.GC() // try to cleanup the mess from the initialization
78+
79+
b.Run("name="+c.name, func(b *testing.B) {
80+
var err error
6981
for i := 0; i < b.N; i++ {
70-
_, err = checker.Check(tree, config)
71-
if err != nil {
72-
b.Fatal(err)
82+
j := i
83+
if j < 0 || j >= len(trees) {
84+
b.StopTimer()
85+
invalidateTrees(trees...)
86+
j = 0
87+
b.StartTimer()
7388
}
89+
90+
_, err = checker.Check(trees[j], config)
91+
}
92+
b.StopTimer()
93+
if err != nil {
94+
b.Fatal(err)
7495
}
7596
})
7697
}
98+
}
99+
100+
type visitorFunc func(*ast.Node)
77101

102+
func (f visitorFunc) Visit(node *ast.Node) { f(node) }
103+
104+
func invalidateTrees(trees ...*parser.Tree) {
105+
for _, tree := range trees {
106+
ast.Walk(&tree.Node, visitorFunc(func(node *ast.Node) {
107+
(*node).SetNature(nature.Nature{})
108+
}))
109+
}
78110
}
79111

80112
type recursive struct {

0 commit comments

Comments
 (0)