Debian Codegraph @

src/go/format/benchmark_test.go

raw
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // This file provides a simple framework to add benchmarks
6 // based on generated input (source) files.
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 // array1 generates an array literal with n elements of the form:
22 //
23 // var _ = [...]byte{
24 // // 0
25 // 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26 // 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
27 // 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
28 // 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
29 // 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
30 // // 40
31 // 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
32 // 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
33 // ...
34 func array1(buf *bytes.Buffer, n int) {
35 buf.WriteString("var _ = [...]byte{\n")
36 for i := 0; i < n; {
37 if i%10 == 0 {
38 fmt.Fprintf(buf, "\t// %d\n", i)
39 }
40 buf.WriteByte('\t')
41 for j := 0; j < 8; j++ {
42 fmt.Fprintf(buf, "0x%02x, ", byte(i))
43 i++
44 }
45 buf.WriteString("\n")
46 }
47 buf.WriteString("}\n")
48 }
49
50 var tests = []struct {
51 name string
52 gen func(*bytes.Buffer, int)
53 n int
54 }{
55 {"array1", array1, 10000},
56 // add new test cases here as needed
57 }
58
59 func BenchmarkFormat(b *testing.B) {
60 var src bytes.Buffer
61 for _, t := range tests {
62 src.Reset()
63 src.WriteString("package p\n")
64 t.gen(&src, t.n)
65 data := src.Bytes()
66
67 if *debug {
68 filename := t.name + ".src"
69 err := os.WriteFile(filename, data, 0660)
70 if err != nil {
71 b.Fatalf("couldn't write %s: %v", filename, err)
72 }
73 }
74
75 b.Run(fmt.Sprintf("%s-%d", t.name, t.n), func(b *testing.B) {
76 b.SetBytes(int64(len(data)))
77 b.ReportAllocs()
78 b.ResetTimer()
79 for i := 0; i < b.N; i++ {
80 var err error
81 sink, err = format.Source(data)
82 if err != nil {
83 b.Fatal(err)
84 }
85 }
86 })
87 }
88 }
89
90 var sink []byte