ChannelMojo: Let MessagePipeReader wait "peer closed" signal as well.
[chromium-blink-merge.git] / tools / profile_chrome / main.py
blob0f9f1498e3ecacfa84c22e732d4536d9f2a8f028
1 #!/usr/bin/env python
3 # Copyright 2014 The Chromium Authors. All rights reserved.
4 # Use of this source code is governed by a BSD-style license that can be
5 # found in the LICENSE file.
7 import logging
8 import optparse
9 import os
10 import sys
11 import webbrowser
13 from profile_chrome import chrome_controller
14 from profile_chrome import flags
15 from profile_chrome import perf_controller
16 from profile_chrome import profiler
17 from profile_chrome import systrace_controller
18 from profile_chrome import ui
20 from pylib import android_commands
21 from pylib.device import device_utils
24 _DEFAULT_CHROME_CATEGORIES = '_DEFAULT_CHROME_CATEGORIES'
27 def _ComputeChromeCategories(options):
28 categories = []
29 if options.trace_frame_viewer:
30 categories.append('disabled-by-default-cc.debug')
31 if options.trace_ubercompositor:
32 categories.append('disabled-by-default-cc.debug*')
33 if options.trace_gpu:
34 categories.append('disabled-by-default-gpu.debug*')
35 if options.trace_flow:
36 categories.append('disabled-by-default-toplevel.flow')
37 if options.trace_memory:
38 categories.append('disabled-by-default-memory')
39 if options.trace_scheduler:
40 categories.append('disabled-by-default-blink.scheduler')
41 categories.append('disabled-by-default-cc.debug.scheduler')
42 categories.append('disabled-by-default-renderer.scheduler')
43 if options.chrome_categories:
44 categories += options.chrome_categories.split(',')
45 return categories
48 def _ComputeSystraceCategories(options):
49 if not options.systrace_categories:
50 return []
51 return options.systrace_categories.split(',')
54 def _ComputePerfCategories(options):
55 if not perf_controller.PerfProfilerController.IsSupported():
56 return []
57 if not options.perf_categories:
58 return []
59 return options.perf_categories.split(',')
62 def _OptionalValueCallback(default_value):
63 def callback(option, _, __, parser):
64 value = default_value
65 if parser.rargs and not parser.rargs[0].startswith('-'):
66 value = parser.rargs.pop(0)
67 setattr(parser.values, option.dest, value)
68 return callback
71 def _CreateOptionParser():
72 parser = optparse.OptionParser(description='Record about://tracing profiles '
73 'from Android browsers. See http://dev.'
74 'chromium.org/developers/how-tos/trace-event-'
75 'profiling-tool for detailed instructions for '
76 'profiling.')
78 timed_options = optparse.OptionGroup(parser, 'Timed tracing')
79 timed_options.add_option('-t', '--time', help='Profile for N seconds and '
80 'download the resulting trace.', metavar='N',
81 type='float')
82 parser.add_option_group(timed_options)
84 cont_options = optparse.OptionGroup(parser, 'Continuous tracing')
85 cont_options.add_option('--continuous', help='Profile continuously until '
86 'stopped.', action='store_true')
87 cont_options.add_option('--ring-buffer', help='Use the trace buffer as a '
88 'ring buffer and save its contents when stopping '
89 'instead of appending events into one long trace.',
90 action='store_true')
91 parser.add_option_group(cont_options)
93 chrome_opts = optparse.OptionGroup(parser, 'Chrome tracing options')
94 chrome_opts.add_option('-c', '--categories', help='Select Chrome tracing '
95 'categories with comma-delimited wildcards, '
96 'e.g., "*", "cat1*,-cat1a". Omit this option to trace '
97 'Chrome\'s default categories. Chrome tracing can be '
98 'disabled with "--categories=\'\'". Use "list" to '
99 'see the available categories.',
100 metavar='CHROME_CATEGORIES', dest='chrome_categories',
101 default=_DEFAULT_CHROME_CATEGORIES)
102 chrome_opts.add_option('--trace-cc',
103 help='Deprecated, use --trace-frame-viewer.',
104 action='store_true')
105 chrome_opts.add_option('--trace-frame-viewer',
106 help='Enable enough trace categories for '
107 'compositor frame viewing.', action='store_true')
108 chrome_opts.add_option('--trace-ubercompositor',
109 help='Enable enough trace categories for '
110 'ubercompositor frame data.', action='store_true')
111 chrome_opts.add_option('--trace-gpu', help='Enable extra trace categories '
112 'for GPU data.', action='store_true')
113 chrome_opts.add_option('--trace-flow', help='Enable extra trace categories '
114 'for IPC message flows.', action='store_true')
115 chrome_opts.add_option('--trace-memory', help='Enable extra trace categories '
116 'for memory profile. (tcmalloc required)',
117 action='store_true')
118 chrome_opts.add_option('--trace-scheduler', help='Enable extra trace '
119 'categories for scheduler state',
120 action='store_true')
121 parser.add_option_group(chrome_opts)
123 parser.add_option_group(flags.SystraceOptions(parser))
125 if perf_controller.PerfProfilerController.IsSupported():
126 perf_opts = optparse.OptionGroup(parser, 'Perf profiling options')
127 perf_opts.add_option('-p', '--perf', help='Capture a perf profile with '
128 'the chosen comma-delimited event categories. '
129 'Samples CPU cycles by default. Use "list" to see '
130 'the available sample types.', action='callback',
131 default='', callback=_OptionalValueCallback('cycles'),
132 metavar='PERF_CATEGORIES', dest='perf_categories')
133 parser.add_option_group(perf_opts)
135 parser.add_option_group(flags.OutputOptions(parser))
137 browsers = sorted(profiler.GetSupportedBrowsers().keys())
138 parser.add_option('-b', '--browser', help='Select among installed browsers. '
139 'One of ' + ', '.join(browsers) + ', "stable" is used by '
140 'default.', type='choice', choices=browsers,
141 default='stable')
142 parser.add_option('-v', '--verbose', help='Verbose logging.',
143 action='store_true')
144 parser.add_option('-z', '--compress', help='Compress the resulting trace '
145 'with gzip. ', action='store_true')
146 parser.add_option('-d', '--device', help='The Android device ID to use.'
147 'If not specified, only 0 or 1 connected devices are '
148 'supported.', default=None)
149 return parser
152 def main():
153 parser = _CreateOptionParser()
154 options, _args = parser.parse_args()
155 if options.trace_cc:
156 parser.parse_error("""--trace-cc is deprecated.
158 For basic jank busting uses, use --trace-frame-viewer
159 For detailed study of ubercompositor, pass --trace-ubercompositor.
161 When in doubt, just try out --trace-frame-viewer.
162 """)
164 if options.verbose:
165 logging.getLogger().setLevel(logging.DEBUG)
167 devices = android_commands.GetAttachedDevices()
168 device = None
169 if options.device in devices:
170 device = options.device
171 elif not options.device and len(devices) == 1:
172 device = devices[0]
173 if not device:
174 parser.error('Use -d/--device to select a device:\n' + '\n'.join(devices))
175 device = device_utils.DeviceUtils(device)
176 package_info = profiler.GetSupportedBrowsers()[options.browser]
178 if options.chrome_categories in ['list', 'help']:
179 ui.PrintMessage('Collecting record categories list...', eol='')
180 record_categories = []
181 disabled_by_default_categories = []
182 record_categories, disabled_by_default_categories = \
183 chrome_controller.ChromeTracingController.GetCategories(
184 device, package_info)
186 ui.PrintMessage('done')
187 ui.PrintMessage('Record Categories:')
188 ui.PrintMessage('\n'.join('\t%s' % item \
189 for item in sorted(record_categories)))
191 ui.PrintMessage('\nDisabled by Default Categories:')
192 ui.PrintMessage('\n'.join('\t%s' % item \
193 for item in sorted(disabled_by_default_categories)))
195 return 0
197 if options.systrace_categories in ['list', 'help']:
198 ui.PrintMessage('\n'.join(
199 systrace_controller.SystraceController.GetCategories(device)))
200 return 0
202 if (perf_controller.PerfProfilerController.IsSupported() and
203 options.perf_categories in ['list', 'help']):
204 ui.PrintMessage('\n'.join(
205 perf_controller.PerfProfilerController.GetCategories(device)))
206 return 0
208 if not options.time and not options.continuous:
209 ui.PrintMessage('Time interval or continuous tracing should be specified.')
210 return 1
212 chrome_categories = _ComputeChromeCategories(options)
213 systrace_categories = _ComputeSystraceCategories(options)
214 perf_categories = _ComputePerfCategories(options)
216 if chrome_categories and 'webview' in systrace_categories:
217 logging.warning('Using the "webview" category in systrace together with '
218 'Chrome tracing results in duplicate trace events.')
220 enabled_controllers = []
221 if chrome_categories:
222 enabled_controllers.append(
223 chrome_controller.ChromeTracingController(device,
224 package_info,
225 chrome_categories,
226 options.ring_buffer,
227 options.trace_memory))
228 if systrace_categories:
229 enabled_controllers.append(
230 systrace_controller.SystraceController(device,
231 systrace_categories,
232 options.ring_buffer))
234 if perf_categories:
235 enabled_controllers.append(
236 perf_controller.PerfProfilerController(device,
237 perf_categories))
239 if not enabled_controllers:
240 ui.PrintMessage('No trace categories enabled.')
241 return 1
243 if options.output:
244 options.output = os.path.expanduser(options.output)
245 result = profiler.CaptureProfile(
246 enabled_controllers,
247 options.time if not options.continuous else 0,
248 output=options.output,
249 compress=options.compress,
250 write_json=options.json)
251 if options.view:
252 if sys.platform == 'darwin':
253 os.system('/usr/bin/open %s' % os.path.abspath(result))
254 else:
255 webbrowser.open(result)