blob: 99693e619b088768e54dd79eea8d5c6e5a78a374 [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"
Damien Neile89e6242019-05-13 23:55:40 -070014 "google.golang.org/protobuf/proto"
Damien Neil53b05a52019-04-08 07:56:05 -070015)
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) {
Damien Neild0b07492019-12-16 12:59:13 -080028 for _, test := range testValidMessages {
Damien Neil53b05a52019-04-08 07:56:05 -070029 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 }
Damien Neildd380ab2019-07-08 15:19:51 -070041 if err != nil && !test.partial {
Damien Neil53b05a52019-04-08 07:56:05 -070042 b.Fatal(err)
43 }
44 }
45 })
46 })
47 }
48 }
49}
50
51// BenchmarkDecode benchmarks decoding all the test messages.
52func BenchmarkDecode(b *testing.B) {
Damien Neild0b07492019-12-16 12:59:13 -080053 for _, test := range testValidMessages {
Damien Neil53b05a52019-04-08 07:56:05 -070054 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) {
Damien Neil53b05a52019-04-08 07:56:05 -070058 for pb.Next() {
Damien Neildd380ab2019-07-08 15:19:51 -070059 m := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message)
60 v1 := m.(protoV1.Message)
Damien Neil53b05a52019-04-08 07:56:05 -070061 var err error
62 if *benchV1 {
63 err = protoV1.Unmarshal(test.wire, v1)
64 } else {
65 err = opts.Unmarshal(test.wire, m)
66 }
Damien Neildd380ab2019-07-08 15:19:51 -070067 if err != nil && !test.partial {
Damien Neil53b05a52019-04-08 07:56:05 -070068 b.Fatal(err)
69 }
70 }
71 })
72 })
73 }
74 }
75}