2019-04-08 14:56:05 +00:00
|
|
|
// Copyright 2019 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package proto_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
protoV1 "github.com/golang/protobuf/proto"
|
2019-05-14 06:55:40 +00:00
|
|
|
"google.golang.org/protobuf/proto"
|
2019-04-08 14:56:05 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// The results of these microbenchmarks are unlikely to correspond well
|
|
|
|
// to real world peformance. They are mainly useful as a quick check to
|
|
|
|
// detect unexpected regressions and for profiling specific cases.
|
|
|
|
|
|
|
|
var (
|
|
|
|
benchV1 = flag.Bool("v1", false, "benchmark the v1 implementation")
|
|
|
|
allowPartial = flag.Bool("allow_partial", false, "set AllowPartial")
|
|
|
|
)
|
|
|
|
|
|
|
|
// BenchmarkEncode benchmarks encoding all the test messages.
|
|
|
|
func BenchmarkEncode(b *testing.B) {
|
2019-12-16 20:59:13 +00:00
|
|
|
for _, test := range testValidMessages {
|
2019-04-08 14:56:05 +00:00
|
|
|
for _, want := range test.decodeTo {
|
|
|
|
v1 := want.(protoV1.Message)
|
|
|
|
opts := proto.MarshalOptions{AllowPartial: *allowPartial}
|
|
|
|
b.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(b *testing.B) {
|
|
|
|
b.RunParallel(func(pb *testing.PB) {
|
|
|
|
for pb.Next() {
|
|
|
|
var err error
|
|
|
|
if *benchV1 {
|
|
|
|
_, err = protoV1.Marshal(v1)
|
|
|
|
} else {
|
|
|
|
_, err = opts.Marshal(want)
|
|
|
|
}
|
2019-07-08 22:19:51 +00:00
|
|
|
if err != nil && !test.partial {
|
2019-04-08 14:56:05 +00:00
|
|
|
b.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// BenchmarkDecode benchmarks decoding all the test messages.
|
|
|
|
func BenchmarkDecode(b *testing.B) {
|
2019-12-16 20:59:13 +00:00
|
|
|
for _, test := range testValidMessages {
|
2019-04-08 14:56:05 +00:00
|
|
|
for _, want := range test.decodeTo {
|
|
|
|
opts := proto.UnmarshalOptions{AllowPartial: *allowPartial}
|
|
|
|
b.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(b *testing.B) {
|
|
|
|
b.RunParallel(func(pb *testing.PB) {
|
|
|
|
for pb.Next() {
|
2019-07-08 22:19:51 +00:00
|
|
|
m := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message)
|
|
|
|
v1 := m.(protoV1.Message)
|
2019-04-08 14:56:05 +00:00
|
|
|
var err error
|
|
|
|
if *benchV1 {
|
|
|
|
err = protoV1.Unmarshal(test.wire, v1)
|
|
|
|
} else {
|
|
|
|
err = opts.Unmarshal(test.wire, m)
|
|
|
|
}
|
2019-07-08 22:19:51 +00:00
|
|
|
if err != nil && !test.partial {
|
2019-04-08 14:56:05 +00:00
|
|
|
b.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|