run_microbenchmark.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #!/usr/bin/env python3
  2. # Copyright 2017 gRPC authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import html
  17. import multiprocessing
  18. import os
  19. import subprocess
  20. import sys
  21. import python_utils.jobset as jobset
  22. import python_utils.start_port_server as start_port_server
  23. sys.path.append(
  24. os.path.join(os.path.dirname(sys.argv[0]), '..', 'profiling',
  25. 'microbenchmarks', 'bm_diff'))
  26. import bm_constants
  27. flamegraph_dir = os.path.join(os.path.expanduser('~'), 'FlameGraph')
  28. os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
  29. if not os.path.exists('reports'):
  30. os.makedirs('reports')
  31. start_port_server.start_port_server()
  32. def fnize(s):
  33. out = ''
  34. for c in s:
  35. if c in '<>, /':
  36. if len(out) and out[-1] == '_':
  37. continue
  38. out += '_'
  39. else:
  40. out += c
  41. return out
  42. # index html
  43. index_html = """
  44. <html>
  45. <head>
  46. <title>Microbenchmark Results</title>
  47. </head>
  48. <body>
  49. """
  50. def heading(name):
  51. global index_html
  52. index_html += "<h1>%s</h1>\n" % name
  53. def link(txt, tgt):
  54. global index_html
  55. index_html += "<p><a href=\"%s\">%s</a></p>\n" % (html.escape(
  56. tgt, quote=True), html.escape(txt))
  57. def text(txt):
  58. global index_html
  59. index_html += "<p><pre>%s</pre></p>\n" % html.escape(txt)
  60. def _bazel_build_benchmark(bm_name, cfg):
  61. """Build given benchmark with bazel"""
  62. subprocess.check_call([
  63. 'tools/bazel', 'build',
  64. '--config=%s' % cfg,
  65. '//test/cpp/microbenchmarks:%s' % bm_name
  66. ])
  67. def collect_latency(bm_name, args):
  68. """generate latency profiles"""
  69. benchmarks = []
  70. profile_analysis = []
  71. cleanup = []
  72. heading('Latency Profiles: %s' % bm_name)
  73. _bazel_build_benchmark(bm_name, 'basicprof')
  74. for line in subprocess.check_output([
  75. 'bazel-bin/test/cpp/microbenchmarks/%s' % bm_name,
  76. '--benchmark_list_tests'
  77. ]).decode('UTF-8').splitlines():
  78. link(line, '%s.txt' % fnize(line))
  79. benchmarks.append(
  80. jobset.JobSpec([
  81. 'bazel-bin/test/cpp/microbenchmarks/%s' % bm_name,
  82. '--benchmark_filter=^%s$' % line, '--benchmark_min_time=0.05'
  83. ],
  84. environ={
  85. 'GRPC_LATENCY_TRACE': '%s.trace' % fnize(line)
  86. },
  87. shortname='profile-%s' % fnize(line)))
  88. profile_analysis.append(
  89. jobset.JobSpec([
  90. sys.executable,
  91. 'tools/profiling/latency_profile/profile_analyzer.py',
  92. '--source',
  93. '%s.trace' % fnize(line), '--fmt', 'simple', '--out',
  94. 'reports/%s.txt' % fnize(line)
  95. ],
  96. timeout_seconds=20 * 60,
  97. shortname='analyze-%s' % fnize(line)))
  98. cleanup.append(jobset.JobSpec(['rm', '%s.trace' % fnize(line)]))
  99. # periodically flush out the list of jobs: profile_analysis jobs at least
  100. # consume upwards of five gigabytes of ram in some cases, and so analysing
  101. # hundreds of them at once is impractical -- but we want at least some
  102. # concurrency or the work takes too long
  103. if len(benchmarks) >= min(16, multiprocessing.cpu_count()):
  104. # run up to half the cpu count: each benchmark can use up to two cores
  105. # (one for the microbenchmark, one for the data flush)
  106. jobset.run(benchmarks,
  107. maxjobs=max(1,
  108. multiprocessing.cpu_count() / 2))
  109. jobset.run(profile_analysis, maxjobs=multiprocessing.cpu_count())
  110. jobset.run(cleanup, maxjobs=multiprocessing.cpu_count())
  111. benchmarks = []
  112. profile_analysis = []
  113. cleanup = []
  114. # run the remaining benchmarks that weren't flushed
  115. if len(benchmarks):
  116. jobset.run(benchmarks, maxjobs=max(1, multiprocessing.cpu_count() / 2))
  117. jobset.run(profile_analysis, maxjobs=multiprocessing.cpu_count())
  118. jobset.run(cleanup, maxjobs=multiprocessing.cpu_count())
  119. def collect_perf(bm_name, args):
  120. """generate flamegraphs"""
  121. heading('Flamegraphs: %s' % bm_name)
  122. _bazel_build_benchmark(bm_name, 'mutrace')
  123. benchmarks = []
  124. profile_analysis = []
  125. cleanup = []
  126. for line in subprocess.check_output([
  127. 'bazel-bin/test/cpp/microbenchmarks/%s' % bm_name,
  128. '--benchmark_list_tests'
  129. ]).decode('UTF-8').splitlines():
  130. link(line, '%s.svg' % fnize(line))
  131. benchmarks.append(
  132. jobset.JobSpec([
  133. 'perf', 'record', '-o',
  134. '%s-perf.data' % fnize(line), '-g', '-F', '997',
  135. 'bazel-bin/test/cpp/microbenchmarks/%s' % bm_name,
  136. '--benchmark_filter=^%s$' % line, '--benchmark_min_time=10'
  137. ],
  138. shortname='perf-%s' % fnize(line)))
  139. profile_analysis.append(
  140. jobset.JobSpec(
  141. [
  142. 'tools/run_tests/performance/process_local_perf_flamegraphs.sh'
  143. ],
  144. environ={
  145. 'PERF_BASE_NAME': fnize(line),
  146. 'OUTPUT_DIR': 'reports',
  147. 'OUTPUT_FILENAME': fnize(line),
  148. },
  149. shortname='flame-%s' % fnize(line)))
  150. cleanup.append(jobset.JobSpec(['rm', '%s-perf.data' % fnize(line)]))
  151. cleanup.append(jobset.JobSpec(['rm', '%s-out.perf' % fnize(line)]))
  152. # periodically flush out the list of jobs: temporary space required for this
  153. # processing is large
  154. if len(benchmarks) >= 20:
  155. # run up to half the cpu count: each benchmark can use up to two cores
  156. # (one for the microbenchmark, one for the data flush)
  157. jobset.run(benchmarks, maxjobs=1)
  158. jobset.run(profile_analysis, maxjobs=multiprocessing.cpu_count())
  159. jobset.run(cleanup, maxjobs=multiprocessing.cpu_count())
  160. benchmarks = []
  161. profile_analysis = []
  162. cleanup = []
  163. # run the remaining benchmarks that weren't flushed
  164. if len(benchmarks):
  165. jobset.run(benchmarks, maxjobs=1)
  166. jobset.run(profile_analysis, maxjobs=multiprocessing.cpu_count())
  167. jobset.run(cleanup, maxjobs=multiprocessing.cpu_count())
  168. def run_summary(bm_name, cfg, base_json_name):
  169. _bazel_build_benchmark(bm_name, cfg)
  170. cmd = [
  171. 'bazel-bin/test/cpp/microbenchmarks/%s' % bm_name,
  172. '--benchmark_out=%s.%s.json' % (base_json_name, cfg),
  173. '--benchmark_out_format=json'
  174. ]
  175. if args.summary_time is not None:
  176. cmd += ['--benchmark_min_time=%d' % args.summary_time]
  177. return subprocess.check_output(cmd).decode('UTF-8')
  178. def collect_summary(bm_name, args):
  179. # no counters, run microbenchmark and add summary
  180. # both to HTML report and to console.
  181. nocounters_heading = 'Summary: %s [no counters]' % bm_name
  182. nocounters_summary = run_summary(bm_name, 'opt', bm_name)
  183. heading(nocounters_heading)
  184. text(nocounters_summary)
  185. print(nocounters_heading)
  186. print(nocounters_summary)
  187. # with counters, run microbenchmark and add summary
  188. # both to HTML report and to console.
  189. counters_heading = 'Summary: %s [with counters]' % bm_name
  190. counters_summary = run_summary(bm_name, 'counters', bm_name)
  191. heading(counters_heading)
  192. text(counters_summary)
  193. print(counters_heading)
  194. print(counters_summary)
  195. if args.bq_result_table:
  196. with open('%s.csv' % bm_name, 'w') as f:
  197. f.write(
  198. subprocess.check_output([
  199. 'tools/profiling/microbenchmarks/bm2bq.py',
  200. '%s.counters.json' % bm_name,
  201. '%s.opt.json' % bm_name
  202. ]).decode('UTF-8'))
  203. subprocess.check_call(
  204. ['bq', 'load',
  205. '%s' % args.bq_result_table,
  206. '%s.csv' % bm_name])
  207. collectors = {
  208. 'latency': collect_latency,
  209. 'perf': collect_perf,
  210. 'summary': collect_summary,
  211. }
  212. argp = argparse.ArgumentParser(description='Collect data from microbenchmarks')
  213. argp.add_argument('-c',
  214. '--collect',
  215. choices=sorted(collectors.keys()),
  216. nargs='*',
  217. default=sorted(collectors.keys()),
  218. help='Which collectors should be run against each benchmark')
  219. argp.add_argument('-b',
  220. '--benchmarks',
  221. choices=bm_constants._AVAILABLE_BENCHMARK_TESTS,
  222. default=bm_constants._AVAILABLE_BENCHMARK_TESTS,
  223. nargs='+',
  224. type=str,
  225. help='Which microbenchmarks should be run')
  226. argp.add_argument(
  227. '--bq_result_table',
  228. default='',
  229. type=str,
  230. help='Upload results from summary collection to a specified bigquery table.'
  231. )
  232. argp.add_argument(
  233. '--summary_time',
  234. default=None,
  235. type=int,
  236. help='Minimum time to run benchmarks for the summary collection')
  237. args = argp.parse_args()
  238. try:
  239. for collect in args.collect:
  240. for bm_name in args.benchmarks:
  241. collectors[collect](bm_name, args)
  242. finally:
  243. if not os.path.exists('reports'):
  244. os.makedirs('reports')
  245. index_html += "</body>\n</html>\n"
  246. with open('reports/index.html', 'w') as f:
  247. f.write(index_html)