py_benchmark.py 6.2 KB

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