blob: a38d11ba9d3c04e7570bbd0a396c81a5610f0bbe [file] [log] [blame]
Damien Neil53b05a52019-04-08 07:56:05 -07001// 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 protoV1 "github.com/golang/protobuf/proto"
14 "github.com/golang/protobuf/v2/proto"
15)
16
17// The results of these microbenchmarks are unlikely to correspond well
18// to real world peformance. They are mainly useful as a quick check to
19// detect unexpected regressions and for profiling specific cases.
20
21var (
22 benchV1 = flag.Bool("v1", false, "benchmark the v1 implementation")
23 allowPartial = flag.Bool("allow_partial", false, "set AllowPartial")
24)
25
26// BenchmarkEncode benchmarks encoding all the test messages.
27func BenchmarkEncode(b *testing.B) {
28 for _, test := range testProtos {
29 for _, want := range test.decodeTo {
30 v1 := want.(protoV1.Message)
31 opts := proto.MarshalOptions{AllowPartial: *allowPartial}
32 b.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(b *testing.B) {
33 b.RunParallel(func(pb *testing.PB) {
34 for pb.Next() {
35 var err error
36 if *benchV1 {
37 _, err = protoV1.Marshal(v1)
38 } else {
39 _, err = opts.Marshal(want)
40 }
41 if err != nil {
42 b.Fatal(err)
43 }
44 }
45 })
46 })
47 }
48 }
49}
50
51// BenchmarkDecode benchmarks decoding all the test messages.
52func BenchmarkDecode(b *testing.B) {
53 for _, test := range testProtos {
54 for _, want := range test.decodeTo {
55 opts := proto.UnmarshalOptions{AllowPartial: *allowPartial}
56 b.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(b *testing.B) {
57 b.RunParallel(func(pb *testing.PB) {
58 m := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message)
59 v1 := m.(protoV1.Message)
60 for pb.Next() {
61 var err error
62 if *benchV1 {
63 err = protoV1.Unmarshal(test.wire, v1)
64 } else {
65 err = opts.Unmarshal(test.wire, m)
66 }
67 if err != nil {
68 b.Fatal(err)
69 }
70 }
71 })
72 })
73 }
74 }
75}