Collect chrome://tracing data in Web benchmarks (#53879)
Collect chrome://tracing data in Web benchmarks
This commit is contained in:
@@ -191,31 +191,54 @@ class BenchTextCachedLayout extends RawRecorder {
|
||||
/// build are unique.
|
||||
int _counter = 0;
|
||||
|
||||
/// Measures how expensive it is to construct material checkboxes.
|
||||
/// Which mode to run [BenchBuildColorsGrid] in.
|
||||
enum _TestMode {
|
||||
/// Uses the HTML rendering backend with the canvas 2D text layout.
|
||||
useCanvasTextLayout,
|
||||
|
||||
/// Uses the HTML rendering backend with the DOM text layout.
|
||||
useDomTextLayout,
|
||||
|
||||
/// Uses CanvasKit for everything.
|
||||
useCanvasKit,
|
||||
}
|
||||
|
||||
/// Measures how expensive it is to construct a realistic text-heavy piece of UI.
|
||||
///
|
||||
/// Creates a 10x10 grid of tristate checkboxes.
|
||||
/// The benchmark constructs a tabbed view, where each tab displays a list of
|
||||
/// colors. Each color's description is made of several [Text] nodes.
|
||||
class BenchBuildColorsGrid extends WidgetBuildRecorder {
|
||||
BenchBuildColorsGrid({@required this.useCanvas})
|
||||
: super(name: useCanvas ? canvasBenchmarkName : domBenchmarkName);
|
||||
BenchBuildColorsGrid.canvas()
|
||||
: mode = _TestMode.useCanvasTextLayout, super(name: canvasBenchmarkName);
|
||||
BenchBuildColorsGrid.dom()
|
||||
: mode = _TestMode.useDomTextLayout, super(name: domBenchmarkName);
|
||||
BenchBuildColorsGrid.canvasKit()
|
||||
: mode = _TestMode.useCanvasKit, super(name: canvasKitBenchmarkName);
|
||||
|
||||
static const String domBenchmarkName = 'text_dom_color_grid';
|
||||
static const String canvasBenchmarkName = 'text_canvas_color_grid';
|
||||
static const String canvasKitBenchmarkName = 'text_canvas_kit_color_grid';
|
||||
|
||||
/// Whether to use the new canvas-based text measurement implementation.
|
||||
final bool useCanvas;
|
||||
final _TestMode mode;
|
||||
|
||||
num _textLayoutMicros = 0;
|
||||
|
||||
@override
|
||||
void setUpAll() {
|
||||
_useCanvasText(useCanvas);
|
||||
Future<void> setUpAll() async {
|
||||
if (mode == _TestMode.useCanvasTextLayout) {
|
||||
_useCanvasText(true);
|
||||
}
|
||||
if (mode == _TestMode.useDomTextLayout) {
|
||||
_useCanvasText(false);
|
||||
}
|
||||
_onBenchmark((String name, num value) {
|
||||
_textLayoutMicros += value;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void tearDownAll() {
|
||||
Future<void> tearDownAll() async {
|
||||
_useCanvasText(null);
|
||||
_onBenchmark(null);
|
||||
}
|
||||
@@ -230,7 +253,8 @@ class BenchBuildColorsGrid extends WidgetBuildRecorder {
|
||||
void frameDidDraw() {
|
||||
// We need to do this before calling [super.frameDidDraw] because the latter
|
||||
// updates the value of [showWidget] in preparation for the next frame.
|
||||
if (showWidget) {
|
||||
// TODO(yjbanov): https://github.com/flutter/flutter/issues/53877
|
||||
if (showWidget && mode != _TestMode.useCanvasKit) {
|
||||
profile.addDataPoint(
|
||||
'text_layout',
|
||||
Duration(microseconds: _textLayoutMicros.toInt()),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:html' as html;
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
@@ -28,6 +29,8 @@ const int kMaxSampleCount = 10 * kMinSampleCount;
|
||||
|
||||
/// The number of samples used to extract metrics, such as noise, means,
|
||||
/// max/min values.
|
||||
///
|
||||
/// Keep this constant in sync with the same constant defined in `dev/devicelab/lib/framework/browser.dart`.
|
||||
const int _kMeasuredSampleCount = 10;
|
||||
|
||||
/// Maximum tolerated noise level.
|
||||
@@ -44,6 +47,50 @@ Duration timeAction(VoidCallback action) {
|
||||
return stopwatch.elapsed;
|
||||
}
|
||||
|
||||
/// A function that performs asynchronous work.
|
||||
typedef AsyncVoidCallback = Future<void> Function();
|
||||
|
||||
/// Runs the benchmark using the given [recorder].
|
||||
///
|
||||
/// Notifies about "set up" and "tear down" events via the [setUpAllDidRun]
|
||||
/// and [tearDownAllWillRun] callbacks.
|
||||
@sealed
|
||||
class Runner {
|
||||
/// Creates a runner for the [recorder].
|
||||
///
|
||||
/// All arguments must not be null.
|
||||
Runner({
|
||||
@required this.recorder,
|
||||
@required this.setUpAllDidRun,
|
||||
@required this.tearDownAllWillRun,
|
||||
});
|
||||
|
||||
/// The recorder that will run and record the benchmark.
|
||||
final Recorder recorder;
|
||||
|
||||
/// Called immediately after [Recorder.setUpAll] future is resolved.
|
||||
///
|
||||
/// This is useful, for example, to kick off a profiler or a tracer such that
|
||||
/// the "set up" computations are not included in the metrics.
|
||||
final AsyncVoidCallback setUpAllDidRun;
|
||||
|
||||
/// Called just before calling [Recorder.tearDownAll].
|
||||
///
|
||||
/// This is useful, for example, to stop a profiler or a tracer such that
|
||||
/// the "tear down" computations are not included in the metrics.
|
||||
final AsyncVoidCallback tearDownAllWillRun;
|
||||
|
||||
/// Runs the benchmark and reports the results.
|
||||
Future<Profile> run() async {
|
||||
await recorder.setUpAll();
|
||||
await setUpAllDidRun();
|
||||
final Profile profile = await recorder.run();
|
||||
await tearDownAllWillRun();
|
||||
await recorder.tearDownAll();
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
|
||||
/// Base class for benchmark recorders.
|
||||
///
|
||||
/// Each benchmark recorder has a [name] and a [run] method at a minimum.
|
||||
@@ -56,8 +103,20 @@ abstract class Recorder {
|
||||
/// prefix.
|
||||
final String name;
|
||||
|
||||
/// Called once before all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time setup work that's needed for the
|
||||
/// benchmark.
|
||||
Future<void> setUpAll() async {}
|
||||
|
||||
/// The implementation of the benchmark that will produce a [Profile].
|
||||
Future<Profile> run();
|
||||
|
||||
/// Called once after all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time clean up work after the benchmark is
|
||||
/// complete.
|
||||
Future<void> tearDownAll() async {}
|
||||
}
|
||||
|
||||
/// A recorder for benchmarking raw execution of Dart code.
|
||||
@@ -86,18 +145,6 @@ abstract class Recorder {
|
||||
abstract class RawRecorder extends Recorder {
|
||||
RawRecorder({@required String name}) : super._(name);
|
||||
|
||||
/// Called once before all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time setup work that's needed for the
|
||||
/// benchmark.
|
||||
void setUpAll() {}
|
||||
|
||||
/// Called once after all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time clean up work after the benchmark is
|
||||
/// complete.
|
||||
void tearDownAll() {}
|
||||
|
||||
/// The body of the benchmark.
|
||||
///
|
||||
/// This is the part that records measurements of the benchmark.
|
||||
@@ -107,12 +154,10 @@ abstract class RawRecorder extends Recorder {
|
||||
@nonVirtual
|
||||
Future<Profile> run() async {
|
||||
final Profile profile = Profile(name: name);
|
||||
setUpAll();
|
||||
do {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
body(profile);
|
||||
} while (profile.shouldContinue());
|
||||
tearDownAll();
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
@@ -162,24 +207,36 @@ abstract class SceneBuilderRecorder extends Recorder {
|
||||
final Profile profile = Profile(name: name);
|
||||
|
||||
window.onBeginFrame = (_) {
|
||||
onBeginFrame();
|
||||
try {
|
||||
startMeasureFrame();
|
||||
onBeginFrame();
|
||||
} catch (error, stackTrace) {
|
||||
profileCompleter.completeError(error, stackTrace);
|
||||
rethrow;
|
||||
}
|
||||
};
|
||||
window.onDrawFrame = () {
|
||||
profile.record('drawFrameDuration', () {
|
||||
final SceneBuilder sceneBuilder = SceneBuilder();
|
||||
onDrawFrame(sceneBuilder);
|
||||
profile.record('sceneBuildDuration', () {
|
||||
final Scene scene = sceneBuilder.build();
|
||||
profile.record('windowRenderDuration', () {
|
||||
window.render(scene);
|
||||
try {
|
||||
profile.record('drawFrameDuration', () {
|
||||
final SceneBuilder sceneBuilder = SceneBuilder();
|
||||
onDrawFrame(sceneBuilder);
|
||||
profile.record('sceneBuildDuration', () {
|
||||
final Scene scene = sceneBuilder.build();
|
||||
profile.record('windowRenderDuration', () {
|
||||
window.render(scene);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
endMeasureFrame();
|
||||
|
||||
if (profile.shouldContinue()) {
|
||||
window.scheduleFrame();
|
||||
} else {
|
||||
profileCompleter.complete(profile);
|
||||
if (profile.shouldContinue()) {
|
||||
window.scheduleFrame();
|
||||
} else {
|
||||
profileCompleter.complete(profile);
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
profileCompleter.completeError(error, stackTrace);
|
||||
rethrow;
|
||||
}
|
||||
};
|
||||
window.scheduleFrame();
|
||||
@@ -270,12 +327,14 @@ abstract class WidgetRecorder extends Recorder
|
||||
@override
|
||||
@mustCallSuper
|
||||
void frameWillDraw() {
|
||||
startMeasureFrame();
|
||||
_drawFrameStopwatch = Stopwatch()..start();
|
||||
}
|
||||
|
||||
@override
|
||||
@mustCallSuper
|
||||
void frameDidDraw() {
|
||||
endMeasureFrame();
|
||||
profile.addDataPoint('drawFrameDuration', _drawFrameStopwatch.elapsed);
|
||||
|
||||
if (profile.shouldContinue()) {
|
||||
@@ -323,18 +382,6 @@ abstract class WidgetBuildRecorder extends Recorder
|
||||
/// consider using [WidgetRecorder].
|
||||
Widget createWidget();
|
||||
|
||||
/// Called once before all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time setup work that's needed for the
|
||||
/// benchmark.
|
||||
void setUpAll() {}
|
||||
|
||||
/// Called once after all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time clean up work after the benchmark is
|
||||
/// complete.
|
||||
void tearDownAll() {}
|
||||
|
||||
@override
|
||||
Profile profile;
|
||||
|
||||
@@ -361,7 +408,10 @@ abstract class WidgetBuildRecorder extends Recorder
|
||||
@override
|
||||
@mustCallSuper
|
||||
void frameWillDraw() {
|
||||
_drawFrameStopwatch = Stopwatch()..start();
|
||||
if (showWidget) {
|
||||
startMeasureFrame();
|
||||
_drawFrameStopwatch = Stopwatch()..start();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -369,6 +419,7 @@ abstract class WidgetBuildRecorder extends Recorder
|
||||
void frameDidDraw() {
|
||||
// Only record frames that show the widget.
|
||||
if (showWidget) {
|
||||
endMeasureFrame();
|
||||
profile.addDataPoint('drawFrameDuration', _drawFrameStopwatch.elapsed);
|
||||
}
|
||||
|
||||
@@ -388,13 +439,11 @@ abstract class WidgetBuildRecorder extends Recorder
|
||||
@override
|
||||
Future<Profile> run() {
|
||||
profile = Profile(name: name);
|
||||
setUpAll();
|
||||
final _RecordingWidgetsBinding binding =
|
||||
_RecordingWidgetsBinding.ensureInitialized();
|
||||
binding._beginRecording(this, _WidgetBuildRecorderHost(this));
|
||||
|
||||
_profileCompleter.future.whenComplete(() {
|
||||
tearDownAll();
|
||||
profile = null;
|
||||
});
|
||||
return _profileCompleter.future;
|
||||
@@ -433,7 +482,9 @@ class _WidgetBuildRecorderHostState extends State<_WidgetBuildRecorderHost> {
|
||||
/// calculations will only apply to the latest [_kMeasuredSampleCount] data
|
||||
/// points.
|
||||
class Timeseries {
|
||||
Timeseries();
|
||||
Timeseries(this.name);
|
||||
|
||||
final String name;
|
||||
|
||||
/// List of all the values that have been recorded.
|
||||
///
|
||||
@@ -450,14 +501,28 @@ class Timeseries {
|
||||
/// because of the sample size limit.
|
||||
int get count => _allValues.length;
|
||||
|
||||
double get average => _computeMean(_measuredValues);
|
||||
/// Computes the average value of the measured values.
|
||||
double get average => _computeAverage(name, _measuredValues);
|
||||
|
||||
/// Computes the standard deviation of the measured values.
|
||||
double get standardDeviation =>
|
||||
_computeStandardDeviationForPopulation(_measuredValues);
|
||||
_computeStandardDeviationForPopulation(name, _measuredValues);
|
||||
|
||||
double get noise => standardDeviation / average;
|
||||
/// Computes noise as a multiple of the [average] value.
|
||||
///
|
||||
/// This value can be multiplied by 100.0 to get noise as a percentage of
|
||||
/// the average.
|
||||
///
|
||||
/// If [average] is zero, treats the result as perfect score, returns zero.
|
||||
double get noise => average > 0.0 ? standardDeviation / average : 0.0;
|
||||
|
||||
/// Adds a value to this timeseries.
|
||||
void add(num value) {
|
||||
if (value < 0.0) {
|
||||
throw StateError(
|
||||
'Timeseries $name: negative metric values are not supported. Got: $value',
|
||||
);
|
||||
}
|
||||
_measuredValues.add(value);
|
||||
_allValues.add(value);
|
||||
// Don't let the [_measuredValues] list grow beyond [_kMeasuredSampleCount].
|
||||
@@ -488,7 +553,7 @@ class Profile {
|
||||
}
|
||||
|
||||
void addDataPoint(String key, Duration duration) {
|
||||
scoreData.putIfAbsent(key, () => Timeseries()).add(duration.inMicroseconds);
|
||||
scoreData.putIfAbsent(key, () => Timeseries(key)).add(duration.inMicroseconds);
|
||||
}
|
||||
|
||||
/// Decides whether the data collected so far is sufficient to stop, or
|
||||
@@ -599,7 +664,11 @@ class Profile {
|
||||
}
|
||||
|
||||
/// Computes the arithmetic mean (or average) of given [values].
|
||||
double _computeMean(Iterable<num> values) {
|
||||
double _computeAverage(String label, Iterable<num> values) {
|
||||
if (values.isEmpty) {
|
||||
throw StateError('$label: attempted to compute an average of an empty value list.');
|
||||
}
|
||||
|
||||
final num sum = values.reduce((num a, num b) => a + b);
|
||||
return sum / values.length;
|
||||
}
|
||||
@@ -611,8 +680,11 @@ double _computeMean(Iterable<num> values) {
|
||||
/// See also:
|
||||
///
|
||||
/// * https://en.wikipedia.org/wiki/Standard_deviation
|
||||
double _computeStandardDeviationForPopulation(Iterable<num> population) {
|
||||
final double mean = _computeMean(population);
|
||||
double _computeStandardDeviationForPopulation(String label, Iterable<num> population) {
|
||||
if (population.isEmpty) {
|
||||
throw StateError('$label: attempted to compute the standard deviation of empty population.');
|
||||
}
|
||||
final double mean = _computeAverage(label, population);
|
||||
final double sumOfSquaredDeltas = population.fold<double>(
|
||||
0.0,
|
||||
(double previous, num value) => previous += math.pow(value - mean, 2),
|
||||
@@ -676,17 +748,21 @@ class _RecordingWidgetsBinding extends BindingBase
|
||||
|
||||
// Fail hard and fast on errors. Benchmarks should not have any errors.
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
if (_hasErrored) {
|
||||
return;
|
||||
}
|
||||
_listener._onError(details.exception, details.stack);
|
||||
_hasErrored = true;
|
||||
_haltBenchmarkWithError(details.exception, details.stack);
|
||||
originalOnError(details);
|
||||
};
|
||||
_listener = recorder;
|
||||
runApp(widget);
|
||||
}
|
||||
|
||||
void _haltBenchmarkWithError(dynamic error, StackTrace stackTrace) {
|
||||
if (_hasErrored) {
|
||||
return;
|
||||
}
|
||||
_listener._onError(error, stackTrace);
|
||||
_hasErrored = true;
|
||||
}
|
||||
|
||||
/// To avoid calling [Profile.shouldContinue] every time [scheduleFrame] is
|
||||
/// called, we cache this value at the beginning of the frame.
|
||||
bool _benchmarkStopped = false;
|
||||
@@ -697,8 +773,13 @@ class _RecordingWidgetsBinding extends BindingBase
|
||||
if (_hasErrored) {
|
||||
return;
|
||||
}
|
||||
_benchmarkStopped = !_listener.profile.shouldContinue();
|
||||
super.handleBeginFrame(rawTimeStamp);
|
||||
try {
|
||||
_benchmarkStopped = !_listener.profile.shouldContinue();
|
||||
super.handleBeginFrame(rawTimeStamp);
|
||||
} catch (error, stackTrace) {
|
||||
_haltBenchmarkWithError(error, stackTrace);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -715,8 +796,40 @@ class _RecordingWidgetsBinding extends BindingBase
|
||||
if (_hasErrored) {
|
||||
return;
|
||||
}
|
||||
_listener.frameWillDraw();
|
||||
super.handleDrawFrame();
|
||||
_listener.frameDidDraw();
|
||||
try {
|
||||
_listener.frameWillDraw();
|
||||
super.handleDrawFrame();
|
||||
_listener.frameDidDraw();
|
||||
} catch (error, stackTrace) {
|
||||
_haltBenchmarkWithError(error, stackTrace);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int _currentFrameNumber = 1;
|
||||
|
||||
/// Adds a marker indication the beginning of frame rendering.
|
||||
///
|
||||
/// This adds an event to the performance trace used to find measured frames in
|
||||
/// Chrome tracing data. The tracing data contains all frames, but some
|
||||
/// benchmarks are only interested in a subset of frames. For example,
|
||||
/// [WidgetBuildRecorder] only measures frames that build widgets, and ignores
|
||||
/// frames that clear the screen.
|
||||
void startMeasureFrame() {
|
||||
html.window.performance.mark('measured_frame_start#$_currentFrameNumber');
|
||||
}
|
||||
|
||||
/// Signals the end of a measured frame.
|
||||
///
|
||||
/// See [startMeasureFrame] for details on what this instrumentation is used
|
||||
/// for.
|
||||
void endMeasureFrame() {
|
||||
html.window.performance.mark('measured_frame_end#$_currentFrameNumber');
|
||||
html.window.performance.measure(
|
||||
'measured_frame',
|
||||
'measured_frame_start#$_currentFrameNumber',
|
||||
'measured_frame_end#$_currentFrameNumber',
|
||||
);
|
||||
_currentFrameNumber += 1;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user