bench_test.go 2.0 KB

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