github.com/shijuvar/go@v0.0.0-20141209052335-e8f13700b70c/src/go/printer/performance_test.go (about) 1 // Copyright 2009 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 implements a simple printer performance benchmark: 6 // go test -bench=BenchmarkPrint 7 8 package printer 9 10 import ( 11 "bytes" 12 "go/ast" 13 "go/parser" 14 "io" 15 "io/ioutil" 16 "log" 17 "testing" 18 ) 19 20 var testfile *ast.File 21 22 func testprint(out io.Writer, file *ast.File) { 23 if err := (&Config{TabIndent | UseSpaces, 8, 0}).Fprint(out, fset, file); err != nil { 24 log.Fatalf("print error: %s", err) 25 } 26 } 27 28 // cannot initialize in init because (printer) Fprint launches goroutines. 29 func initialize() { 30 const filename = "testdata/parser.go" 31 32 src, err := ioutil.ReadFile(filename) 33 if err != nil { 34 log.Fatalf("%s", err) 35 } 36 37 file, err := parser.ParseFile(fset, filename, src, parser.ParseComments) 38 if err != nil { 39 log.Fatalf("%s", err) 40 } 41 42 var buf bytes.Buffer 43 testprint(&buf, file) 44 if !bytes.Equal(buf.Bytes(), src) { 45 log.Fatalf("print error: %s not idempotent", filename) 46 } 47 48 testfile = file 49 } 50 51 func BenchmarkPrint(b *testing.B) { 52 if testfile == nil { 53 initialize() 54 } 55 for i := 0; i < b.N; i++ { 56 testprint(ioutil.Discard, testfile) 57 } 58 }