linux_perf_report.py 6.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
#! /usr/bin/python2
#
# Copyright 2016 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#

import argparse
import collections
import re
import subprocess
import sys


__DESCRIPTION = """
Processes a perf.data sample file and reports the hottest Ignition bytecodes,
or write an input file for flamegraph.pl.
"""


__HELP_EPILOGUE = """
examples:
  # Get a flamegraph for Ignition bytecode handlers on Octane benchmark,
  # without considering the time spent compiling JS code, entry trampoline
  # samples and other non-Ignition samples.
  #
  $ tools/run-perf.sh out/x64.release/d8 \\
        --ignition --noturbo --nocrankshaft run.js
  $ tools/ignition/linux_perf_report.py --flamegraph -o out.collapsed
  $ flamegraph.pl --colors js out.collapsed > out.svg

  # Same as above, but show all samples, including time spent compiling JS code,
  # entry trampoline samples and other samples.
  $ # ...
  $ tools/ignition/linux_perf_report.py \\
      --flamegraph --show-all -o out.collapsed
  $ # ...

  # Same as above, but show full function signatures in the flamegraph.
  $ # ...
  $ tools/ignition/linux_perf_report.py \\
      --flamegraph --show-full-signatures -o out.collapsed
  $ # ...

  # See the hottest bytecodes on Octane benchmark, by number of samples.
  #
  $ tools/run-perf.sh out/x64.release/d8 \\
        --ignition --noturbo --nocrankshaft octane/run.js
  $ tools/ignition/linux_perf_report.py
"""


COMPILER_SYMBOLS_RE = re.compile(
  r"v8::internal::(?:\(anonymous namespace\)::)?Compile|v8::internal::Parser")


def strip_function_parameters(symbol):
  if symbol[-1] != ')': return symbol
  pos = 1
  parenthesis_count = 0
  for c in reversed(symbol):
    if c == ')':
      parenthesis_count += 1
    elif c == '(':
      parenthesis_count -= 1
    if parenthesis_count == 0:
      break
    else:
      pos += 1
  return symbol[:-pos]


def collapsed_callchains_generator(perf_stream, show_all=False,
                                   show_full_signatures=False):
  current_chain = []
  skip_until_end_of_chain = False
  compiler_symbol_in_chain = False

  for line in perf_stream:
    # Lines starting with a "#" are comments, skip them.
    if line[0] == "#":
      continue

    line = line.strip()

    # Empty line signals the end of the callchain.
    if not line:
      if not skip_until_end_of_chain and current_chain and show_all:
        current_chain.append("[other]")
        yield current_chain
      # Reset parser status.
      current_chain = []
      skip_until_end_of_chain = False
      compiler_symbol_in_chain = False
      continue

    if skip_until_end_of_chain:
      continue

    symbol = line.split(" ", 1)[1]
    if not show_full_signatures:
      symbol = strip_function_parameters(symbol)
    current_chain.append(symbol)

    if symbol.startswith("BytecodeHandler:"):
      yield current_chain
      skip_until_end_of_chain = True
    elif symbol == "Stub:CEntryStub" and compiler_symbol_in_chain:
      if show_all:
        current_chain[-1] = "[compiler]"
        yield current_chain
      skip_until_end_of_chain = True
    elif COMPILER_SYMBOLS_RE.match(symbol):
      compiler_symbol_in_chain = True
    elif symbol == "Builtin:InterpreterEntryTrampoline":
      if len(current_chain) == 1:
        yield ["[entry trampoline]"]
118
      else:
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        # If we see an InterpreterEntryTrampoline which is not at the top of the
        # chain and doesn't have a BytecodeHandler above it, then we have
        # skipped the top BytecodeHandler due to the top-level stub not building
        # a frame. File the chain in the [misattributed] bucket.
        current_chain[-1] = "[misattributed]"
        yield current_chain
      skip_until_end_of_chain = True


def calculate_samples_count_per_callchain(callchains):
  chain_counters = collections.defaultdict(int)
  for callchain in callchains:
    key = ";".join(reversed(callchain))
    chain_counters[key] += 1
  return chain_counters.items()


def calculate_samples_count_per_handler(callchains):
  def strip_handler_prefix_if_any(handler):
    return handler if handler[0] == "[" else handler.split(":", 1)[1]

  handler_counters = collections.defaultdict(int)
  for callchain in callchains:
    handler = strip_handler_prefix_if_any(callchain[-1])
    handler_counters[handler] += 1
  return handler_counters.items()


def write_flamegraph_input_file(output_stream, callchains):
  for callchain, count in calculate_samples_count_per_callchain(callchains):
    output_stream.write("{}; {}\n".format(callchain, count))


def write_handlers_report(output_stream, callchains):
  handler_counters = calculate_samples_count_per_handler(callchains)
  samples_num = sum(counter for _, counter in handler_counters)
  # Sort by decreasing number of samples
  handler_counters.sort(key=lambda entry: entry[1], reverse=True)
  for bytecode_name, count in handler_counters:
    output_stream.write(
      "{}\t{}\t{:.3f}%\n".format(bytecode_name, count,
                                 100. * count / samples_num))


def parse_command_line():
  command_line_parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description=__DESCRIPTION,
    epilog=__HELP_EPILOGUE)

  command_line_parser.add_argument(
    "perf_filename",
    help="perf sample file to process (default: perf.data)",
    nargs="?",
    default="perf.data",
    metavar="<perf filename>"
  )
  command_line_parser.add_argument(
    "--flamegraph", "-f",
    help="output an input file for flamegraph.pl, not a report",
    action="store_true",
    dest="output_flamegraph"
  )
  command_line_parser.add_argument(
    "--show-all", "-a",
    help="show samples outside Ignition bytecode handlers",
    action="store_true"
  )
  command_line_parser.add_argument(
    "--show-full-signatures", "-s",
    help="show full signatures instead of function names",
    action="store_true"
  )
  command_line_parser.add_argument(
    "--output", "-o",
    help="output file name (stdout if omitted)",
    type=argparse.FileType('wt'),
    default=sys.stdout,
    metavar="<output filename>",
    dest="output_stream"
  )

  return command_line_parser.parse_args()


def main():
  program_options = parse_command_line()

  perf = subprocess.Popen(["perf", "script", "-f", "ip,sym",
                           "-i", program_options.perf_filename],
                          stdout=subprocess.PIPE)

  callchains = collapsed_callchains_generator(
    perf.stdout, program_options.show_all,
    program_options.show_full_signatures)

  if program_options.output_flamegraph:
    write_flamegraph_input_file(program_options.output_stream, callchains)
  else:
    write_handlers_report(program_options.output_stream, callchains)


if __name__ == "__main__":
  main()