bench_test.go 1.6 KB

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