...
Source file
src/go/format/benchmark_test.go
1
2
3
4
5
6
7
8 package format_test
9
10 import (
11 "bytes"
12 "flag"
13 "fmt"
14 "go/format"
15 "os"
16 "testing"
17 )
18
19 var debug = flag.Bool("debug", false, "write .src files containing formatting input; for debugging")
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 func array1(buf *bytes.Buffer, n int) {
36 buf.WriteString("var _ = [...]byte{\n")
37 for i := 0; i < n; {
38 if i%10 == 0 {
39 fmt.Fprintf(buf, "\t// %d\n", i)
40 }
41 buf.WriteByte('\t')
42 for j := 0; j < 8; j++ {
43 fmt.Fprintf(buf, "0x%02x, ", byte(i))
44 i++
45 }
46 buf.WriteString("\n")
47 }
48 buf.WriteString("}\n")
49 }
50
51 var tests = []struct {
52 name string
53 gen func(*bytes.Buffer, int)
54 n int
55 }{
56 {"array1", array1, 10000},
57
58 }
59
60 func BenchmarkFormat(b *testing.B) {
61 var src bytes.Buffer
62 for _, t := range tests {
63 src.Reset()
64 src.WriteString("package p\n")
65 t.gen(&src, t.n)
66 data := src.Bytes()
67
68 if *debug {
69 filename := t.name + ".src"
70 err := os.WriteFile(filename, data, 0660)
71 if err != nil {
72 b.Fatalf("couldn't write %s: %v", filename, err)
73 }
74 }
75
76 b.Run(fmt.Sprintf("%s-%d", t.name, t.n), func(b *testing.B) {
77 b.SetBytes(int64(len(data)))
78 b.ReportAllocs()
79 b.ResetTimer()
80 for i := 0; i < b.N; i++ {
81 var err error
82 sink, err = format.Source(data)
83 if err != nil {
84 b.Fatal(err)
85 }
86 }
87 })
88 }
89 }
90
91 var sink []byte
92
View as plain text