1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements a simple printer performance benchmark:
// go test -bench=BenchmarkPrint
package printer
import (
"bytes"
"go/ast"
"go/parser"
"io"
"log"
"os"
"testing"
)
var testfile *ast.File
func testprint(out io.Writer, file *ast.File) {
if err := (&Config{TabIndent | UseSpaces | normalizeNumbers, 8, 0}).Fprint(out, fset, file); err != nil {
log.Fatalf("print error: %s", err)
}
}
// cannot initialize in init because (printer) Fprint launches goroutines.
func initialize() {
const filename = "testdata/parser.go"
src, err := os.ReadFile(filename)
if err != nil {
log.Fatalf("%s", err)
}
file, err := parser.ParseFile(fset, filename, src, parser.ParseComments)
if err != nil {
log.Fatalf("%s", err)
}
var buf bytes.Buffer
testprint(&buf, file)
if !bytes.Equal(buf.Bytes(), src) {
log.Fatalf("print error: %s not idempotent", filename)
}
testfile = file
}
func BenchmarkPrint(b *testing.B) {
if testfile == nil {
initialize()
}
for i := 0; i < b.N; i++ {
testprint(io.Discard, testfile)
}
}
|