profile_analyzer.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #!/usr/bin/env python3
  2. # Copyright 2015 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 collections
  17. import hashlib
  18. import json
  19. import math
  20. import sys
  21. import time
  22. from six.moves import zip
  23. import tabulate
  24. SELF_TIME = object()
  25. TIME_FROM_SCOPE_START = object()
  26. TIME_TO_SCOPE_END = object()
  27. TIME_FROM_STACK_START = object()
  28. TIME_TO_STACK_END = object()
  29. TIME_FROM_LAST_IMPORTANT = object()
  30. argp = argparse.ArgumentParser(
  31. description='Process output of basic_prof builds')
  32. argp.add_argument('--source', default='latency_trace.txt', type=str)
  33. argp.add_argument('--fmt', choices=tabulate.tabulate_formats, default='simple')
  34. argp.add_argument('--out', default='-', type=str)
  35. args = argp.parse_args()
  36. class LineItem(object):
  37. def __init__(self, line, indent):
  38. self.tag = line['tag']
  39. self.indent = indent
  40. self.start_time = line['t']
  41. self.end_time = None
  42. self.important = line['imp']
  43. self.filename = line['file']
  44. self.fileline = line['line']
  45. self.times = {}
  46. class ScopeBuilder(object):
  47. def __init__(self, call_stack_builder, line):
  48. self.call_stack_builder = call_stack_builder
  49. self.indent = len(call_stack_builder.stk)
  50. self.top_line = LineItem(line, self.indent)
  51. call_stack_builder.lines.append(self.top_line)
  52. self.first_child_pos = len(call_stack_builder.lines)
  53. def mark(self, line):
  54. line_item = LineItem(line, self.indent + 1)
  55. line_item.end_time = line_item.start_time
  56. self.call_stack_builder.lines.append(line_item)
  57. def finish(self, line):
  58. assert line['tag'] == self.top_line.tag, (
  59. 'expected %s, got %s; thread=%s; t0=%f t1=%f' %
  60. (self.top_line.tag, line['tag'], line['thd'],
  61. self.top_line.start_time, line['t']))
  62. final_time_stamp = line['t']
  63. assert self.top_line.end_time is None
  64. self.top_line.end_time = final_time_stamp
  65. self.top_line.important = self.top_line.important or line['imp']
  66. assert SELF_TIME not in self.top_line.times
  67. self.top_line.times[
  68. SELF_TIME] = final_time_stamp - self.top_line.start_time
  69. for line in self.call_stack_builder.lines[self.first_child_pos:]:
  70. if TIME_FROM_SCOPE_START not in line.times:
  71. line.times[
  72. TIME_FROM_SCOPE_START] = line.start_time - self.top_line.start_time
  73. line.times[TIME_TO_SCOPE_END] = final_time_stamp - line.end_time
  74. class CallStackBuilder(object):
  75. def __init__(self):
  76. self.stk = []
  77. self.signature = hashlib.md5()
  78. self.lines = []
  79. def finish(self):
  80. start_time = self.lines[0].start_time
  81. end_time = self.lines[0].end_time
  82. self.signature = self.signature.hexdigest()
  83. last_important = start_time
  84. for line in self.lines:
  85. line.times[TIME_FROM_STACK_START] = line.start_time - start_time
  86. line.times[TIME_TO_STACK_END] = end_time - line.end_time
  87. line.times[
  88. TIME_FROM_LAST_IMPORTANT] = line.start_time - last_important
  89. if line.important:
  90. last_important = line.end_time
  91. last_important = end_time
  92. def add(self, line):
  93. line_type = line['type']
  94. self.signature.update(line_type.encode('UTF-8'))
  95. self.signature.update(line['tag'].encode('UTF-8'))
  96. if line_type == '{':
  97. self.stk.append(ScopeBuilder(self, line))
  98. return False
  99. elif line_type == '}':
  100. assert self.stk, (
  101. 'expected non-empty stack for closing %s; thread=%s; t=%f' %
  102. (line['tag'], line['thd'], line['t']))
  103. self.stk.pop().finish(line)
  104. if not self.stk:
  105. self.finish()
  106. return True
  107. return False
  108. elif line_type == '.' or line_type == '!':
  109. if self.stk:
  110. self.stk[-1].mark(line)
  111. return False
  112. else:
  113. raise Exception('Unknown line type: \'%s\'' % line_type)
  114. class CallStack(object):
  115. def __init__(self, initial_call_stack_builder):
  116. self.count = 1
  117. self.signature = initial_call_stack_builder.signature
  118. self.lines = initial_call_stack_builder.lines
  119. for line in self.lines:
  120. for key, val in list(line.times.items()):
  121. line.times[key] = [val]
  122. def add(self, call_stack_builder):
  123. assert self.signature == call_stack_builder.signature
  124. self.count += 1
  125. assert len(self.lines) == len(call_stack_builder.lines)
  126. for lsum, line in zip(self.lines, call_stack_builder.lines):
  127. assert lsum.tag == line.tag
  128. assert list(lsum.times.keys()) == list(line.times.keys())
  129. for k, lst in list(lsum.times.items()):
  130. lst.append(line.times[k])
  131. def finish(self):
  132. for line in self.lines:
  133. for lst in list(line.times.values()):
  134. lst.sort()
  135. builder = collections.defaultdict(CallStackBuilder)
  136. call_stacks = collections.defaultdict(CallStack)
  137. lines = 0
  138. start = time.time()
  139. with open(args.source) as f:
  140. for line in f:
  141. lines += 1
  142. inf = json.loads(line)
  143. thd = inf['thd']
  144. cs = builder[thd]
  145. if cs.add(inf):
  146. if cs.signature in call_stacks:
  147. call_stacks[cs.signature].add(cs)
  148. else:
  149. call_stacks[cs.signature] = CallStack(cs)
  150. del builder[thd]
  151. time_taken = time.time() - start
  152. call_stacks = sorted(list(call_stacks.values()),
  153. key=lambda cs: cs.count,
  154. reverse=True)
  155. total_stacks = 0
  156. for cs in call_stacks:
  157. total_stacks += cs.count
  158. cs.finish()
  159. def percentile(N, percent, key=lambda x: x):
  160. """
  161. Find the percentile of an already sorted list of values.
  162. @parameter N - is a list of values. MUST be already sorted.
  163. @parameter percent - a float value from [0.0,1.0].
  164. @parameter key - optional key function to compute value from each element of N.
  165. @return - the percentile of the values
  166. """
  167. if not N:
  168. return None
  169. float_idx = (len(N) - 1) * percent
  170. idx = int(float_idx)
  171. result = key(N[idx])
  172. if idx < len(N) - 1:
  173. # interpolate with the next element's value
  174. result += (float_idx - idx) * (key(N[idx + 1]) - key(N[idx]))
  175. return result
  176. def tidy_tag(tag):
  177. if tag[0:10] == 'GRPC_PTAG_':
  178. return tag[10:]
  179. return tag
  180. def time_string(values):
  181. num_values = len(values)
  182. return '%.1f/%.1f/%.1f' % (1e6 * percentile(values, 0.5), 1e6 * percentile(
  183. values, 0.9), 1e6 * percentile(values, 0.99))
  184. def time_format(idx):
  185. def ent(line, idx=idx):
  186. if idx in line.times:
  187. return time_string(line.times[idx])
  188. return ''
  189. return ent
  190. BANNER = {'simple': 'Count: %(count)d', 'html': '<h1>Count: %(count)d</h1>'}
  191. FORMAT = [
  192. ('TAG', lambda line: '..' * line.indent + tidy_tag(line.tag)),
  193. ('LOC', lambda line: '%s:%d' %
  194. (line.filename[line.filename.rfind('/') + 1:], line.fileline)),
  195. ('IMP', lambda line: '*' if line.important else ''),
  196. ('FROM_IMP', time_format(TIME_FROM_LAST_IMPORTANT)),
  197. ('FROM_STACK_START', time_format(TIME_FROM_STACK_START)),
  198. ('SELF', time_format(SELF_TIME)),
  199. ('TO_STACK_END', time_format(TIME_TO_STACK_END)),
  200. ('FROM_SCOPE_START', time_format(TIME_FROM_SCOPE_START)),
  201. ('SELF', time_format(SELF_TIME)),
  202. ('TO_SCOPE_END', time_format(TIME_TO_SCOPE_END)),
  203. ]
  204. out = sys.stdout
  205. if args.out != '-':
  206. out = open(args.out, 'w')
  207. if args.fmt == 'html':
  208. out.write('<html>')
  209. out.write('<head>')
  210. out.write('<title>Profile Report</title>')
  211. out.write('</head>')
  212. accounted_for = 0
  213. for cs in call_stacks:
  214. out.write('\n')
  215. if args.fmt in BANNER:
  216. out.write(BANNER[args.fmt] % {
  217. 'count': cs.count,
  218. })
  219. header, _ = list(zip(*FORMAT))
  220. table = []
  221. for line in cs.lines:
  222. fields = []
  223. for _, fn in FORMAT:
  224. fields.append(fn(line))
  225. table.append(fields)
  226. out.write(tabulate.tabulate(table, header, tablefmt=args.fmt))
  227. accounted_for += cs.count
  228. if accounted_for > .99 * total_stacks:
  229. break
  230. if args.fmt == 'html':
  231. print('</html>')