bm_diff.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright 2017 gRPC authors.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """ Computes the diff between two bm runs and outputs significant results """
  17. import argparse
  18. import collections
  19. import json
  20. import os
  21. import subprocess
  22. import sys
  23. sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '..'))
  24. import bm_constants
  25. import bm_json
  26. import bm_speedup
  27. import tabulate
  28. verbose = False
  29. def _median(ary):
  30. assert (len(ary))
  31. ary = sorted(ary)
  32. n = len(ary)
  33. if n % 2 == 0:
  34. return (ary[(n - 1) // 2] + ary[(n - 1) // 2 + 1]) / 2.0
  35. else:
  36. return ary[n // 2]
  37. def _args():
  38. argp = argparse.ArgumentParser(
  39. description='Perform diff on microbenchmarks')
  40. argp.add_argument('-t',
  41. '--track',
  42. choices=sorted(bm_constants._INTERESTING),
  43. nargs='+',
  44. default=sorted(bm_constants._INTERESTING),
  45. help='Which metrics to track')
  46. argp.add_argument('-b',
  47. '--benchmarks',
  48. nargs='+',
  49. choices=bm_constants._AVAILABLE_BENCHMARK_TESTS,
  50. default=bm_constants._AVAILABLE_BENCHMARK_TESTS,
  51. help='Which benchmarks to run')
  52. argp.add_argument(
  53. '-l',
  54. '--loops',
  55. type=int,
  56. default=20,
  57. help=
  58. 'Number of times to loops the benchmarks. Must match what was passed to bm_run.py'
  59. )
  60. argp.add_argument('-r',
  61. '--regex',
  62. type=str,
  63. default="",
  64. help='Regex to filter benchmarks run')
  65. argp.add_argument('--counters', dest='counters', action='store_true')
  66. argp.add_argument('--no-counters', dest='counters', action='store_false')
  67. argp.set_defaults(counters=True)
  68. argp.add_argument('-n', '--new', type=str, help='New benchmark name')
  69. argp.add_argument('-o', '--old', type=str, help='Old benchmark name')
  70. argp.add_argument('-v',
  71. '--verbose',
  72. type=bool,
  73. help='Print details of before/after')
  74. args = argp.parse_args()
  75. global verbose
  76. if args.verbose:
  77. verbose = True
  78. assert args.new
  79. assert args.old
  80. return args
  81. def _maybe_print(str):
  82. if verbose:
  83. print(str)
  84. class Benchmark:
  85. def __init__(self):
  86. self.samples = {
  87. True: collections.defaultdict(list),
  88. False: collections.defaultdict(list)
  89. }
  90. self.final = {}
  91. self.speedup = {}
  92. def add_sample(self, track, data, new):
  93. for f in track:
  94. if f in data:
  95. self.samples[new][f].append(float(data[f]))
  96. def process(self, track, new_name, old_name):
  97. for f in sorted(track):
  98. new = self.samples[True][f]
  99. old = self.samples[False][f]
  100. if not new or not old:
  101. continue
  102. mdn_diff = abs(_median(new) - _median(old))
  103. _maybe_print('%s: %s=%r %s=%r mdn_diff=%r' %
  104. (f, new_name, new, old_name, old, mdn_diff))
  105. s = bm_speedup.speedup(new, old, 1e-5)
  106. self.speedup[f] = s
  107. if abs(s) > 3:
  108. if mdn_diff > 0.5:
  109. self.final[f] = '%+d%%' % s
  110. return self.final.keys()
  111. def skip(self):
  112. return not self.final
  113. def row(self, flds):
  114. return [self.final[f] if f in self.final else '' for f in flds]
  115. def speedup(self, name):
  116. if name in self.speedup:
  117. return self.speedup[name]
  118. return None
  119. def _read_json(filename, badjson_files, nonexistant_files):
  120. stripped = ".".join(filename.split(".")[:-2])
  121. try:
  122. with open(filename) as f:
  123. r = f.read()
  124. return json.loads(r)
  125. except IOError as e:
  126. if stripped in nonexistant_files:
  127. nonexistant_files[stripped] += 1
  128. else:
  129. nonexistant_files[stripped] = 1
  130. return None
  131. except ValueError as e:
  132. print(r)
  133. if stripped in badjson_files:
  134. badjson_files[stripped] += 1
  135. else:
  136. badjson_files[stripped] = 1
  137. return None
  138. def fmt_dict(d):
  139. return ''.join([" " + k + ": " + str(d[k]) + "\n" for k in d])
  140. def diff(bms, loops, regex, track, old, new, counters):
  141. benchmarks = collections.defaultdict(Benchmark)
  142. badjson_files = {}
  143. nonexistant_files = {}
  144. for bm in bms:
  145. for loop in range(0, loops):
  146. for line in subprocess.check_output([
  147. 'bm_diff_%s/opt/%s' % (old, bm), '--benchmark_list_tests',
  148. '--benchmark_filter=%s' % regex
  149. ]).splitlines():
  150. line = line.decode('UTF-8')
  151. stripped_line = line.strip().replace("/", "_").replace(
  152. "<", "_").replace(">", "_").replace(", ", "_")
  153. js_new_opt = _read_json(
  154. '%s.%s.opt.%s.%d.json' % (bm, stripped_line, new, loop),
  155. badjson_files, nonexistant_files)
  156. js_old_opt = _read_json(
  157. '%s.%s.opt.%s.%d.json' % (bm, stripped_line, old, loop),
  158. badjson_files, nonexistant_files)
  159. if counters:
  160. js_new_ctr = _read_json(
  161. '%s.%s.counters.%s.%d.json' %
  162. (bm, stripped_line, new, loop), badjson_files,
  163. nonexistant_files)
  164. js_old_ctr = _read_json(
  165. '%s.%s.counters.%s.%d.json' %
  166. (bm, stripped_line, old, loop), badjson_files,
  167. nonexistant_files)
  168. else:
  169. js_new_ctr = None
  170. js_old_ctr = None
  171. for row in bm_json.expand_json(js_new_ctr, js_new_opt):
  172. name = row['cpp_name']
  173. if name.endswith('_mean') or name.endswith('_stddev'):
  174. continue
  175. benchmarks[name].add_sample(track, row, True)
  176. for row in bm_json.expand_json(js_old_ctr, js_old_opt):
  177. name = row['cpp_name']
  178. if name.endswith('_mean') or name.endswith('_stddev'):
  179. continue
  180. benchmarks[name].add_sample(track, row, False)
  181. really_interesting = set()
  182. for name, bm in benchmarks.items():
  183. _maybe_print(name)
  184. really_interesting.update(bm.process(track, new, old))
  185. fields = [f for f in track if f in really_interesting]
  186. # figure out the significance of the changes... right now we take the 95%-ile
  187. # benchmark delta %-age, and then apply some hand chosen thresholds
  188. histogram = []
  189. for bm in benchmarks.values():
  190. if bm.skip():
  191. continue
  192. d = bm.speedup['cpu_time']
  193. if d is None:
  194. continue
  195. histogram.append(d)
  196. histogram.sort()
  197. print("histogram of speedups: ", histogram)
  198. if len(histogram) == 0:
  199. significance = 0
  200. else:
  201. delta = histogram[int(len(histogram) * 0.95)]
  202. mul = 1
  203. if delta < 0:
  204. delta = -delta
  205. mul = -1
  206. if delta < 2:
  207. significance = 0
  208. elif delta < 5:
  209. significance = 1
  210. elif delta < 10:
  211. significance = 2
  212. else:
  213. significance = 3
  214. significance *= mul
  215. headers = ['Benchmark'] + fields
  216. rows = []
  217. for name in sorted(benchmarks.keys()):
  218. if benchmarks[name].skip():
  219. continue
  220. rows.append([name] + benchmarks[name].row(fields))
  221. note = None
  222. if len(badjson_files):
  223. note = 'Corrupt JSON data (indicates timeout or crash): \n%s' % fmt_dict(
  224. badjson_files)
  225. if len(nonexistant_files):
  226. if note:
  227. note += '\n\nMissing files (indicates new benchmark): \n%s' % fmt_dict(
  228. nonexistant_files)
  229. else:
  230. note = '\n\nMissing files (indicates new benchmark): \n%s' % fmt_dict(
  231. nonexistant_files)
  232. if rows:
  233. return tabulate.tabulate(rows, headers=headers,
  234. floatfmt='+.2f'), note, significance
  235. else:
  236. return None, note, 0
  237. if __name__ == '__main__':
  238. args = _args()
  239. diff, note = diff(args.benchmarks, args.loops, args.regex, args.track,
  240. args.old, args.new, args.counters)
  241. print('%s\n%s' % (note, diff if diff else "No performance differences"))