py_benchmark.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. from __future__ import print_function
  2. import sys
  3. import os
  4. import timeit
  5. import math
  6. import argparse
  7. import fnmatch
  8. import json
  9. parser = argparse.ArgumentParser(description="Python protobuf benchmark")
  10. parser.add_argument("data_files", metavar="dataFile", nargs="+",
  11. help="testing data files.")
  12. parser.add_argument("--json", action="store_const", dest="json",
  13. const="yes", default="no",
  14. help="Whether to output json results")
  15. parser.add_argument("--behavior_prefix", dest="behavior_prefix",
  16. help="The output json format's behavior's name's prefix",
  17. default="")
  18. # BEGIN CPP GENERATED MESSAGE
  19. parser.add_argument("--cpp_generated", action="store_const",
  20. dest="cpp_generated", const="yes", default="no",
  21. help="Whether to link generated code library")
  22. # END CPP GENERATED MESSAGE
  23. args = parser.parse_args()
  24. # BEGIN CPP GENERATED MESSAGE
  25. # CPP generated code must be linked before importing the generated Python code
  26. # for the descriptor can be found in the pool
  27. if args.cpp_generated != "no":
  28. sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) + "/.libs" )
  29. import libbenchmark_messages
  30. sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) + "/tmp" )
  31. # END CPP GENERATED MESSAGE
  32. import datasets.google_message1.proto2.benchmark_message1_proto2_pb2 as benchmark_message1_proto2_pb2
  33. import datasets.google_message1.proto3.benchmark_message1_proto3_pb2 as benchmark_message1_proto3_pb2
  34. import datasets.google_message2.benchmark_message2_pb2 as benchmark_message2_pb2
  35. import datasets.google_message3.benchmark_message3_pb2 as benchmark_message3_pb2
  36. import datasets.google_message4.benchmark_message4_pb2 as benchmark_message4_pb2
  37. import benchmarks_pb2 as benchmarks_pb2
  38. def run_one_test(filename):
  39. data = open(filename, "rb").read()
  40. benchmark_dataset = benchmarks_pb2.BenchmarkDataset()
  41. benchmark_dataset.ParseFromString(data)
  42. total_bytes = 0
  43. for payload in benchmark_dataset.payload:
  44. total_bytes += len(payload)
  45. benchmark_util = Benchmark(full_iteration=len(benchmark_dataset.payload),
  46. module="py_benchmark",
  47. setup_method="init",
  48. total_bytes=total_bytes)
  49. result={}
  50. result["filename"] = filename
  51. result["message_name"] = benchmark_dataset.message_name
  52. result["benchmarks"] = {}
  53. benchmark_util.set_test_method("parse_from_benchmark")
  54. result["benchmarks"][args.behavior_prefix + "_parse_from_benchmark"] = \
  55. benchmark_util.run_benchmark(setup_method_args='"%s"' % (filename))
  56. benchmark_util.set_test_method("serialize_to_benchmark")
  57. result["benchmarks"][args.behavior_prefix + "_serialize_to_benchmark"] = \
  58. benchmark_util.run_benchmark(setup_method_args='"%s"' % (filename))
  59. return result
  60. def init(filename):
  61. global benchmark_dataset, message_class, message_list, counter, total_bytes
  62. message_list=[]
  63. counter = 0
  64. total_bytes = 0
  65. data = open(filename, "rb").read()
  66. benchmark_dataset = benchmarks_pb2.BenchmarkDataset()
  67. benchmark_dataset.ParseFromString(data)
  68. if benchmark_dataset.message_name == "benchmarks.proto3.GoogleMessage1":
  69. message_class = benchmark_message1_proto3_pb2.GoogleMessage1
  70. elif benchmark_dataset.message_name == "benchmarks.proto2.GoogleMessage1":
  71. message_class = benchmark_message1_proto2_pb2.GoogleMessage1
  72. elif benchmark_dataset.message_name == "benchmarks.proto2.GoogleMessage2":
  73. message_class = benchmark_message2_pb2.GoogleMessage2
  74. elif benchmark_dataset.message_name == "benchmarks.google_message3.GoogleMessage3":
  75. message_class = benchmark_message3_pb2.GoogleMessage3
  76. elif benchmark_dataset.message_name == "benchmarks.google_message4.GoogleMessage4":
  77. message_class = benchmark_message4_pb2.GoogleMessage4
  78. else:
  79. raise IOError("Message %s not found!" % (benchmark_dataset.message_name))
  80. for one_payload in benchmark_dataset.payload:
  81. temp = message_class()
  82. temp.ParseFromString(one_payload)
  83. message_list.append(temp)
  84. total_bytes += len(one_payload)
  85. def parse_from_benchmark():
  86. global counter, message_class, benchmark_dataset
  87. m = message_class().ParseFromString(benchmark_dataset.payload[counter % len(benchmark_dataset.payload)])
  88. counter = counter + 1
  89. def serialize_to_benchmark():
  90. global counter, message_list, message_class
  91. s = message_list[counter % len(benchmark_dataset.payload)].SerializeToString()
  92. counter = counter + 1
  93. class Benchmark:
  94. def __init__(self, module=None, test_method=None,
  95. setup_method=None, total_bytes=None, full_iteration = 1):
  96. self.full_iteration = full_iteration
  97. self.module = module
  98. self.test_method = test_method
  99. self.setup_method = setup_method
  100. self.total_bytes = total_bytes
  101. def set_test_method(self, test_method):
  102. self.test_method = test_method
  103. def full_setup_code(self, setup_method_args=''):
  104. setup_code = ""
  105. setup_code += "from %s import %s\n" % (self.module, self.test_method)
  106. setup_code += "from %s import %s\n" % (self.module, self.setup_method)
  107. setup_code += "%s(%s)\n" % (self.setup_method, setup_method_args)
  108. return setup_code
  109. def dry_run(self, test_method_args='', setup_method_args=''):
  110. return timeit.timeit(stmt="%s(%s)" % (self.test_method, test_method_args),
  111. setup=self.full_setup_code(setup_method_args),
  112. number=self.full_iteration);
  113. def run_benchmark(self, test_method_args='', setup_method_args=''):
  114. reps = self.full_iteration;
  115. t = self.dry_run(test_method_args, setup_method_args);
  116. if t < 3 :
  117. reps = int(math.ceil(3 / t)) * self.full_iteration
  118. if reps != self.full_iteration:
  119. t = timeit.timeit(stmt="%s(%s)" % (self.test_method, test_method_args),
  120. setup=self.full_setup_code(setup_method_args),
  121. number=reps);
  122. return self.total_bytes * 1.0 / 2 ** 20 / (1.0 * t / reps * self.full_iteration)
  123. if __name__ == "__main__":
  124. results = []
  125. for file in args.data_files:
  126. results.append(run_one_test(file))
  127. if args.json != "no":
  128. print(json.dumps(results))
  129. else:
  130. for result in results:
  131. print("Message %s of dataset file %s" % \
  132. (result["message_name"], result["filename"]))
  133. print("Average throughput for parse_from_benchmark: %.2f MB/s" % \
  134. (result["benchmarks"][ \
  135. args.behavior_prefix + "_parse_from_benchmark"]))
  136. print("Average throughput for serialize_to_benchmark: %.2f MB/s" % \
  137. (result["benchmarks"][ \
  138. args.behavior_prefix + "_serialize_to_benchmark"]))
  139. print("")