blob: 9e9a9c1b5d1cb4852dbd0b2e8b668336125adb02 [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
Damien Neile89e6242019-05-13 23:55:40 -070013 "google.golang.org/protobuf/proto"
Damien Neil53b05a52019-04-08 07:56:05 -070014)
15
16// The results of these microbenchmarks are unlikely to correspond well
Kir Kolyshkinbf945562022-05-17 17:29:33 -070017// to real world performance. They are mainly useful as a quick check to
Damien Neil53b05a52019-04-08 07:56:05 -070018// detect unexpected regressions and for profiling specific cases.
19
20var (
Damien Neil53b05a52019-04-08 07:56:05 -070021 allowPartial = flag.Bool("allow_partial", false, "set AllowPartial")
22)
23
24// BenchmarkEncode benchmarks encoding all the test messages.
25func BenchmarkEncode(b *testing.B) {
Damien Neild0b07492019-12-16 12:59:13 -080026 for _, test := range testValidMessages {
Damien Neil53b05a52019-04-08 07:56:05 -070027 for _, want := range test.decodeTo {
Damien Neil53b05a52019-04-08 07:56:05 -070028 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() {
Damien Neilec00e322020-01-09 09:23:52 -080032 _, err := opts.Marshal(want)
Damien Neildd380ab2019-07-08 15:19:51 -070033 if err != nil && !test.partial {
Damien Neil53b05a52019-04-08 07:56:05 -070034 b.Fatal(err)
35 }
36 }
37 })
38 })
39 }
40 }
41}
42
43// BenchmarkDecode benchmarks decoding all the test messages.
44func BenchmarkDecode(b *testing.B) {
Damien Neild0b07492019-12-16 12:59:13 -080045 for _, test := range testValidMessages {
Damien Neil53b05a52019-04-08 07:56:05 -070046 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) {
Damien Neil53b05a52019-04-08 07:56:05 -070050 for pb.Next() {
Damien Neildd380ab2019-07-08 15:19:51 -070051 m := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message)
Damien Neilec00e322020-01-09 09:23:52 -080052 err := opts.Unmarshal(test.wire, m)
Damien Neildd380ab2019-07-08 15:19:51 -070053 if err != nil && !test.partial {
Damien Neil53b05a52019-04-08 07:56:05 -070054 b.Fatal(err)
55 }
56 }
57 })
58 })
59 }
60 }
61}