1// Copyright 2019 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 5package proto_test 6 7import ( 8 "flag" 9 "fmt" 10 "reflect" 11 "testing" 12 13 "google.golang.org/protobuf/proto" 14) 15 16// The results of these microbenchmarks are unlikely to correspond well 17// to real world performance. They are mainly useful as a quick check to 18// detect unexpected regressions and for profiling specific cases. 19 20var ( 21 allowPartial = flag.Bool("allow_partial", false, "set AllowPartial") 22) 23 24// BenchmarkEncode benchmarks encoding all the test messages. 25func BenchmarkEncode(b *testing.B) { 26 for _, test := range testValidMessages { 27 for _, want := range test.decodeTo { 28 opts := proto.MarshalOptions{AllowPartial: *allowPartial} 29 b.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(b *testing.B) { 30 b.RunParallel(func(pb *testing.PB) { 31 for pb.Next() { 32 _, err := opts.Marshal(want) 33 if err != nil && !test.partial { 34 b.Fatal(err) 35 } 36 } 37 }) 38 }) 39 } 40 } 41} 42 43// BenchmarkDecode benchmarks decoding all the test messages. 44func BenchmarkDecode(b *testing.B) { 45 for _, test := range testValidMessages { 46 for _, want := range test.decodeTo { 47 opts := proto.UnmarshalOptions{AllowPartial: *allowPartial} 48 b.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(b *testing.B) { 49 b.RunParallel(func(pb *testing.PB) { 50 for pb.Next() { 51 m := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message) 52 err := opts.Unmarshal(test.wire, m) 53 if err != nil && !test.partial { 54 b.Fatal(err) 55 } 56 } 57 }) 58 }) 59 } 60 } 61} 62