perf_tests.dart 67.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6
import 'dart:convert' show LineSplitter, json, utf8;
7
import 'dart:io';
8
import 'dart:math' as math;
9

10 11
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
12

13 14 15 16 17
import '../framework/devices.dart';
import '../framework/framework.dart';
import '../framework/host_agent.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';
18

19 20 21
/// Must match flutter_driver/lib/src/common.dart.
///
/// Redefined here to avoid taking a dependency on flutter_driver.
Dan Field's avatar
Dan Field committed
22 23 24
String _testOutputDirectory(String testDirectory) {
  return Platform.environment['FLUTTER_TEST_OUTPUTS_DIR'] ?? '$testDirectory/build';
}
25

26 27 28 29 30
TaskFunction createComplexLayoutScrollPerfTest({
  bool measureCpuGpu = true,
  bool badScroll = false,
  bool enableImpeller = false,
}) {
31
  return PerfTest(
32
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
33 34 35
    badScroll
      ? 'test_driver/scroll_perf_bad.dart'
      : 'test_driver/scroll_perf.dart',
36
    'complex_layout_scroll_perf',
37
    measureCpuGpu: measureCpuGpu,
38
    enableImpeller: enableImpeller,
39
  ).run;
40 41
}

42
TaskFunction createTilesScrollPerfTest({bool enableImpeller = false}) {
43
  return PerfTest(
44 45 46
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
    'test_driver/scroll_perf.dart',
    'tiles_scroll_perf',
47
    enableImpeller: enableImpeller,
48 49 50
  ).run;
}

51
TaskFunction createUiKitViewScrollPerfTest({bool enableImpeller = false}) {
52 53
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/platform_views_layout',
54 55 56
    'test_driver/uikit_view_scroll_perf.dart',
    'platform_views_scroll_perf',
    testDriver: 'test_driver/scroll_perf_test.dart',
57
    needsFullTimeline: false,
58
    enableImpeller: enableImpeller,
59 60 61
  ).run;
}

62 63 64 65 66 67 68 69 70 71 72
TaskFunction createUiKitViewScrollPerfNonIntersectingTest({bool enableImpeller = false}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/platform_views_layout',
    'test_driver/uikit_view_scroll_perf_non_intersecting.dart',
    'platform_views_scroll_perf_non_intersecting',
    testDriver: 'test_driver/scroll_perf_non_intersecting_test.dart',
    needsFullTimeline: false,
    enableImpeller: enableImpeller,
  ).run;
}

73 74 75
TaskFunction createAndroidTextureScrollPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/platform_views_layout',
76
    'test_driver/android_view_scroll_perf.dart',
77
    'platform_views_scroll_perf',
78 79 80 81 82 83
    testDriver: 'test_driver/scroll_perf_test.dart',
  ).run;
}

TaskFunction createAndroidViewScrollPerfTest() {
  return PerfTest(
84
    '${flutterDirectory.path}/dev/benchmarks/platform_views_layout_hybrid_composition',
85
    'test_driver/android_view_scroll_perf.dart',
86
    'platform_views_scroll_perf_hybrid_composition',
87
    testDriver: 'test_driver/scroll_perf_test.dart',
88 89 90
  ).run;
}

91 92
TaskFunction createHomeScrollPerfTest() {
  return PerfTest(
93
    '${flutterDirectory.path}/dev/integration_tests/flutter_gallery',
94 95 96 97 98
    'test_driver/scroll_perf.dart',
    'home_scroll_perf',
  ).run;
}

99 100 101
TaskFunction createCullOpacityPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
102
    'test_driver/run_app.dart',
103
    'cull_opacity_perf',
104
    testDriver: 'test_driver/cull_opacity_perf_test.dart',
105 106 107
  ).run;
}

108
TaskFunction createCullOpacityPerfE2ETest() {
109
  return PerfTest.e2e(
110 111 112 113 114
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/cull_opacity_perf_e2e.dart',
  ).run;
}

115 116 117
TaskFunction createCubicBezierPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
118
    'test_driver/run_app.dart',
119
    'cubic_bezier_perf',
120
    testDriver: 'test_driver/cubic_bezier_perf_test.dart',
121
  ).run;
122 123
}

124 125 126 127 128 129 130
TaskFunction createCubicBezierPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/cubic_bezier_perf_e2e.dart',
  ).run;
}

131 132 133 134 135 136 137 138
TaskFunction createFlutterGalleryTransitionsPerfSkSLWarmupTest() {
  return PerfTestWithSkSL(
    '${flutterDirectory.path}/dev/integration_tests/flutter_gallery',
    'test_driver/transitions_perf.dart',
    'transitions',
  ).run;
}

139 140 141 142
TaskFunction createBackdropFilterPerfTest({
    bool measureCpuGpu = true,
    bool enableImpeller = false,
}) {
143 144
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
145
    'test_driver/run_app.dart',
146
    'backdrop_filter_perf',
147
    measureCpuGpu: measureCpuGpu,
148
    testDriver: 'test_driver/backdrop_filter_perf_test.dart',
149
    saveTraceFile: true,
150
    enableImpeller: enableImpeller,
151 152 153
  ).run;
}

154 155 156 157 158 159 160 161 162 163 164
TaskFunction createAnimationWithMicrotasksPerfTest({bool measureCpuGpu = true}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'animation_with_microtasks_perf',
    measureCpuGpu: measureCpuGpu,
    testDriver: 'test_driver/animation_with_microtasks_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

165 166 167 168 169 170 171
TaskFunction createBackdropFilterPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/backdrop_filter_perf_e2e.dart',
  ).run;
}

172
TaskFunction createPostBackdropFilterPerfTest({bool measureCpuGpu = true}) {
173 174
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
175
    'test_driver/run_app.dart',
176
    'post_backdrop_filter_perf',
177
    measureCpuGpu: measureCpuGpu,
178
    testDriver: 'test_driver/post_backdrop_filter_perf_test.dart',
179
    saveTraceFile: true,
180 181 182
  ).run;
}

183 184 185 186
TaskFunction createSimpleAnimationPerfTest({
  bool measureCpuGpu = true,
  bool enableImpeller = false,
}) {
187 188
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
189
    'test_driver/run_app.dart',
190
    'simple_animation_perf',
191
    measureCpuGpu: measureCpuGpu,
192
    testDriver: 'test_driver/simple_animation_perf_test.dart',
193
    saveTraceFile: true,
194
    enableImpeller: enableImpeller,
195
  ).run;
196 197
}

198 199 200 201 202 203 204
TaskFunction createAnimatedPlaceholderPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/animated_placeholder_perf_e2e.dart',
  ).run;
}

205 206 207
TaskFunction createPictureCachePerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
208
    'test_driver/run_app.dart',
209
    'picture_cache_perf',
210
    testDriver: 'test_driver/picture_cache_perf_test.dart',
211 212 213
  ).run;
}

214
TaskFunction createPictureCachePerfE2ETest() {
215
  return PerfTest.e2e(
216 217 218 219 220
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/picture_cache_perf_e2e.dart',
  ).run;
}

221 222 223 224 225 226 227 228 229
TaskFunction createPictureCacheComplexityScoringPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'picture_cache_complexity_scoring_perf',
    testDriver: 'test_driver/picture_cache_complexity_scoring_perf_test.dart',
  ).run;
}

230 231 232 233 234 235 236 237 238 239 240
TaskFunction createOpenPayScrollPerfTest({bool measureCpuGpu = true}) {
  return PerfTest(
    openpayDirectory.path,
    'test_driver/scroll_perf.dart',
    'openpay_scroll_perf',
    measureCpuGpu: measureCpuGpu,
    testDriver: 'test_driver/scroll_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

241
TaskFunction createFlutterGalleryStartupTest({String target = 'lib/main.dart'}) {
242
  return StartupTest(
243
    '${flutterDirectory.path}/dev/integration_tests/flutter_gallery',
244
    target: target,
245
  ).run;
246 247
}

248
TaskFunction createComplexLayoutStartupTest() {
249
  return StartupTest(
250
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
251
  ).run;
252 253
}

254
TaskFunction createFlutterGalleryCompileTest() {
255
  return CompileTest('${flutterDirectory.path}/dev/integration_tests/flutter_gallery').run;
256 257
}

258
TaskFunction createHelloWorldCompileTest() {
259
  return CompileTest('${flutterDirectory.path}/examples/hello_world', reportPackageContentSizes: true).run;
260 261
}

262 263 264 265
TaskFunction createWebCompileTest() {
  return const WebCompileTest().run;
}

266
TaskFunction createComplexLayoutCompileTest() {
267
  return CompileTest('${flutterDirectory.path}/dev/benchmarks/complex_layout').run;
268 269
}

270
TaskFunction createFlutterViewStartupTest() {
271
  return StartupTest(
272 273
      '${flutterDirectory.path}/examples/flutter_view',
      reportMetrics: false,
274 275 276
  ).run;
}

277
TaskFunction createPlatformViewStartupTest() {
278
  return StartupTest(
279 280 281 282 283
    '${flutterDirectory.path}/examples/platform_view',
    reportMetrics: false,
  ).run;
}

284 285 286 287 288
TaskFunction createBasicMaterialCompileTest() {
  return () async {
    const String sampleAppName = 'sample_flutter_app';
    final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName');

289
    rmTree(sampleDir);
290

291
    await inDirectory<void>(Directory.systemTemp, () async {
292
      await flutter('create', options: <String>['--template=app', sampleAppName]);
293 294
    });

295
    if (!sampleDir.existsSync()) {
296
      throw 'Failed to create default Flutter app in ${sampleDir.path}';
297
    }
298

299
    return CompileTest(sampleDir.path).run();
300
  };
301 302
}

303 304 305
TaskFunction createTextfieldPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
306
    'test_driver/run_app.dart',
307
    'textfield_perf',
308
    testDriver: 'test_driver/textfield_perf_test.dart',
309 310 311
  ).run;
}

312 313 314 315 316 317 318
TaskFunction createTextfieldPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/textfield_perf_e2e.dart',
  ).run;
}

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
TaskFunction createStackSizeTest() {
  final String testDirectory =
      '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks';
  const String testTarget = 'test_driver/run_app.dart';
  const String testDriver = 'test_driver/stack_size_perf_test.dart';
  return () {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;
      await device.unlock();
      final String deviceId = device.deviceId;
      await flutter('packages', options: <String>['get']);

      await flutter('drive', options: <String>[
        '--no-android-gradle-daemon',
        '-v',
        '--verbose-system-logs',
        '--profile',
        '-t', testTarget,
        '--driver', testDriver,
        '-d',
        deviceId,
      ]);
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
342
        file('${_testOutputDirectory(testDirectory)}/stack_size.json').readAsStringSync(),
343 344 345 346 347 348 349 350 351 352 353 354 355
      ) as Map<String, dynamic>;

      final Map<String, dynamic> result = <String, dynamic>{
        'stack_size_per_nesting_level': data['stack_size'],
      };
      return TaskResult.success(
        result,
        benchmarkScoreKeys: result.keys.toList(),
      );
    });
  };
}

356 357 358 359 360 361 362 363 364
TaskFunction createFullscreenTextfieldPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'fullscreen_textfield_perf',
    testDriver: 'test_driver/fullscreen_textfield_perf_test.dart',
  ).run;
}

365 366 367
TaskFunction createFullscreenTextfieldPerfE2ETest({
  bool enableImpeller = false,
}) {
368 369 370
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/fullscreen_textfield_perf_e2e.dart',
371
    enableImpeller: enableImpeller,
372 373 374
  ).run;
}

375 376 377 378 379 380 381
TaskFunction createClipperCachePerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/clipper_cache_perf_e2e.dart',
  ).run;
}

382 383 384
TaskFunction createColorFilterAndFadePerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
385
    'test_driver/run_app.dart',
386
    'color_filter_and_fade_perf',
387
    testDriver: 'test_driver/color_filter_and_fade_perf_test.dart',
388
    saveTraceFile: true,
389 390 391
  ).run;
}

392
TaskFunction createColorFilterAndFadePerfE2ETest({bool enableImpeller = false}) {
393 394 395
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/color_filter_and_fade_perf_e2e.dart',
396
    enableImpeller: enableImpeller,
397 398 399
  ).run;
}

400 401 402 403 404 405 406
TaskFunction createColorFilterCachePerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/color_filter_cache_perf_e2e.dart',
  ).run;
}

407 408 409 410 411 412 413
TaskFunction createColorFilterWithUnstableChildPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/color_filter_with_unstable_child_perf_e2e.dart',
  ).run;
}

414 415 416 417 418 419 420
TaskFunction createRasterCacheUseMemoryPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/raster_cache_use_memory_perf_e2e.dart',
  ).run;
}

421 422 423 424 425 426 427
TaskFunction createShaderMaskCachePerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/shader_mask_cache_perf_e2e.dart',
  ).run;
}

428 429 430
TaskFunction createFadingChildAnimationPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
431
    'test_driver/run_app.dart',
432
    'fading_child_animation_perf',
433
    testDriver: 'test_driver/fading_child_animation_perf_test.dart',
434
    saveTraceFile: true,
435 436 437
  ).run;
}

438 439 440
TaskFunction createImageFilteredTransformAnimationPerfTest({
  bool enableImpeller = false,
}) {
441 442
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
443
    'test_driver/run_app.dart',
444
    'imagefiltered_transform_animation_perf',
445
    testDriver: 'test_driver/imagefiltered_transform_animation_perf_test.dart',
446
    saveTraceFile: true,
447
    enableImpeller: enableImpeller,
448 449 450
  ).run;
}

451
TaskFunction createsMultiWidgetConstructPerfE2ETest() {
452
  return PerfTest.e2e(
453 454 455 456 457
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/multi_widget_construction_perf_e2e.dart',
  ).run;
}

458 459 460 461 462 463 464 465
TaskFunction createListTextLayoutPerfE2ETest({bool enableImpeller = false}) {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/list_text_layout_perf_e2e.dart',
    enableImpeller: enableImpeller,
  ).run;
}

Yuqian Li's avatar
Yuqian Li committed
466 467 468 469 470 471 472 473 474 475 476 477
TaskFunction createsScrollSmoothnessPerfTest() {
  final String testDirectory =
      '${flutterDirectory.path}/dev/benchmarks/complex_layout';
  const String testTarget = 'test/measure_scroll_smoothness.dart';
  return () {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;
      await device.unlock();
      final String deviceId = device.deviceId;
      await flutter('packages', options: <String>['get']);

      await flutter('drive', options: <String>[
478
        '--no-android-gradle-daemon',
Yuqian Li's avatar
Yuqian Li committed
479 480 481 482 483 484 485 486
        '-v',
        '--verbose-system-logs',
        '--profile',
        '-t', testTarget,
        '-d',
        deviceId,
      ]);
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
487
        file('${_testOutputDirectory(testDirectory)}/scroll_smoothness_test.json').readAsStringSync(),
Yuqian Li's avatar
Yuqian Li committed
488 489 490 491 492
      ) as Map<String, dynamic>;

      final Map<String, dynamic> result = <String, dynamic>{};
      void addResult(dynamic data, String suffix) {
        assert(data is Map<String, dynamic>);
493 494 495 496 497 498 499 500 501
        if (data is Map<String, dynamic>) {
          const List<String> metricKeys = <String>[
            'janky_count',
            'average_abs_jerk',
            'dropped_frame_count',
          ];
          for (final String key in metricKeys) {
            result[key + suffix] = data[key];
          }
Yuqian Li's avatar
Yuqian Li committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
        }
      }
      addResult(data['resample on with 90Hz input'], '_with_resampler_90Hz');
      addResult(data['resample on with 59Hz input'], '_with_resampler_59Hz');
      addResult(data['resample off with 90Hz input'], '_without_resampler_90Hz');
      addResult(data['resample off with 59Hz input'], '_without_resampler_59Hz');

      return TaskResult.success(
        result,
        benchmarkScoreKeys: result.keys.toList(),
      );
    });
  };
}

517 518 519 520 521 522 523 524 525 526 527 528
TaskFunction createFramePolicyIntegrationTest() {
  final String testDirectory =
      '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks';
  const String testTarget = 'test/frame_policy.dart';
  return () {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;
      await device.unlock();
      final String deviceId = device.deviceId;
      await flutter('packages', options: <String>['get']);

      await flutter('drive', options: <String>[
529
        '--no-android-gradle-daemon',
530 531 532 533 534 535 536 537
        '-v',
        '--verbose-system-logs',
        '--profile',
        '-t', testTarget,
        '-d',
        deviceId,
      ]);
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
538
        file('${_testOutputDirectory(testDirectory)}/frame_policy_event_delay.json').readAsStringSync(),
539 540 541
      ) as Map<String, dynamic>;
      final Map<String, dynamic> fullLiveData = data['fullyLive'] as Map<String, dynamic>;
      final Map<String, dynamic> benchmarkLiveData = data['benchmarkLive'] as Map<String, dynamic>;
542
      final Map<String, dynamic> dataFormatted = <String, dynamic>{
543 544 545 546 547 548 549 550 551 552 553
        'average_delay_fullyLive_millis':
          fullLiveData['average_delay_millis'],
        'average_delay_benchmarkLive_millis':
          benchmarkLiveData['average_delay_millis'],
        '90th_percentile_delay_fullyLive_millis':
          fullLiveData['90th_percentile_delay_millis'],
        '90th_percentile_delay_benchmarkLive_millis':
          benchmarkLiveData['90th_percentile_delay_millis'],
      };

      return TaskResult.success(
554 555
        dataFormatted,
        benchmarkScoreKeys: dataFormatted.keys.toList(),
556 557 558 559 560
      );
    });
  };
}

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
TaskFunction createOpacityPeepholeOneRectPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_one_rect_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeColOfRowsPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_col_of_rows_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeOpacityOfGridPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_opacity_of_grid_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeGridOfOpacityPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_grid_of_opacity_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeFadeTransitionTextPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_fade_transition_text_perf_e2e.dart',
  ).run;
}

596 597 598 599 600 601 602 603 604 605 606 607 608 609
TaskFunction createOpacityPeepholeGridOfAlphaSaveLayersPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_grid_of_alpha_savelayers_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeColOfAlphaSaveLayerRowsPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_col_of_alpha_savelayer_rows_perf_e2e.dart',
  ).run;
}

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
TaskFunction createGradientDynamicPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/gradient_dynamic_perf_e2e.dart',
  ).run;
}

TaskFunction createGradientConsistentPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/gradient_consistent_perf_e2e.dart',
  ).run;
}

TaskFunction createGradientStaticPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/gradient_static_perf_e2e.dart',
  ).run;
}

631 632 633
TaskFunction createAnimatedComplexOpacityPerfE2ETest({
  bool enableImpeller = false,
}) {
634 635 636
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/animated_complex_opacity_perf_e2e.dart',
637
    enableImpeller: enableImpeller,
638 639 640
  ).run;
}

641 642 643 644 645 646 647 648 649 650 651
TaskFunction createAnimatedComplexImageFilteredPerfE2ETest({
  bool enableImpeller = false,
}) {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/animated_complex_image_filtered_perf_e2e.dart',
    enableImpeller: enableImpeller,
  ).run;
}


652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
Map<String, dynamic> _average(List<Map<String, dynamic>> results, int iterations) {
  final Map<String, dynamic> tally = <String, dynamic>{};
  for (final Map<String, dynamic> item in results) {
    item.forEach((String key, dynamic value) {
      if (tally.containsKey(key)) {
        tally[key] = (tally[key] as int) + (value as int);
      } else {
        tally[key] = value;
      }
    });
  }
  tally.forEach((String key, dynamic value) {
    tally[key] = (value as int) ~/ iterations;
  });
  return tally;
}

669 670
/// Measure application startup performance.
class StartupTest {
671
  const StartupTest(this.testDirectory, { this.reportMetrics = true, this.target = 'lib/main.dart' });
672 673

  final String testDirectory;
674
  final bool reportMetrics;
675
  final String target;
676

677
  Future<TaskResult> run() async {
678
    return inDirectory<TaskResult>(testDirectory, () async {
679
      final Device device = await devices.workingDevice;
680
      await device.unlock();
681
      const int iterations = 5;
682
      final List<Map<String, dynamic>> results = <Map<String, dynamic>>[];
683 684

      section('Building application');
685
      String? applicationBinaryPath;
686 687 688 689 690 691 692
      switch (deviceOperatingSystem) {
        case DeviceOperatingSystem.android:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm,android-arm64',
693
            '--target=$target',
694 695 696
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
          break;
697 698 699 700 701 702
        case DeviceOperatingSystem.androidArm:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm',
703
            '--target=$target',
704 705 706
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
          break;
707 708 709 710 711 712
        case DeviceOperatingSystem.androidArm64:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm64',
713
            '--target=$target',
714 715 716
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
          break;
717 718 719
        case DeviceOperatingSystem.fake:
        case DeviceOperatingSystem.fuchsia:
          break;
720
        case DeviceOperatingSystem.ios:
721
        case DeviceOperatingSystem.macos:
722
          await flutter('build', options: <String>[
723
            if (deviceOperatingSystem == DeviceOperatingSystem.ios) 'ios' else 'macos',
724 725
             '-v',
            '--profile',
726
            '--target=$target',
727
          ]);
728 729
          final String buildRoot = path.join(testDirectory, 'build');
          applicationBinaryPath = _findDarwinAppInBuildDirectory(buildRoot);
730
          break;
731
        case DeviceOperatingSystem.windows:
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
          await flutter('build', options: <String>[
            'windows',
            '-v',
            '--profile',
            '--target=$target',
          ]);
          final String basename = path.basename(testDirectory);
          applicationBinaryPath = path.join(
            testDirectory,
            'build',
            'windows',
            'runner',
            'Profile',
            '$basename.exe'
          );
747 748 749
          break;
      }

750 751
      const int maxFailures = 3;
      int currentFailures = 0;
752
      for (int i = 0; i < iterations; i += 1) {
753
        final int result = await flutter('run', options: <String>[
754
          '--no-android-gradle-daemon',
755
          '--no-publish-port',
756 757 758
          '--verbose',
          '--profile',
          '--trace-startup',
759
          '--target=$target',
760
          '-d',
761 762 763
          device.deviceId,
          if (applicationBinaryPath != null)
            '--use-application-binary=$applicationBinaryPath',
764 765 766
         ], canFail: true);
        if (result == 0) {
          final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
767
            file('${_testOutputDirectory(testDirectory)}/start_up_info.json').readAsStringSync(),
768 769 770 771
          ) as Map<String, dynamic>;
          results.add(data);
        } else {
          currentFailures += 1;
772 773 774 775 776 777 778
          if (hostAgent.dumpDirectory != null) {
            await flutter(
              'screenshot',
              options: <String>[
                '-d',
                device.deviceId,
                '--out',
779
                hostAgent.dumpDirectory!
780 781 782 783 784 785
                    .childFile('screenshot_startup_failure_$currentFailures.png')
                    .path,
              ],
              canFail: true,
            );
          }
786 787 788 789 790
          i -= 1;
          if (currentFailures == maxFailures) {
            return TaskResult.failure('Application failed to start $maxFailures times');
          }
        }
791 792 793 794 795 796

        await flutter('install', options: <String>[
          '--uninstall-only',
          '-d',
          device.deviceId,
        ]);
797 798 799
      }

      final Map<String, dynamic> averageResults = _average(results, iterations);
800

801
      if (!reportMetrics) {
802
        return TaskResult.success(averageResults);
803
      }
804

805
      return TaskResult.success(averageResults, benchmarkScoreKeys: <String>[
806
        'timeToFirstFrameMicros',
807
        'timeToFirstFrameRasterizedMicros',
808 809 810 811 812
      ]);
    });
  }
}

813 814 815 816 817 818 819 820 821 822 823
/// A one-off test to verify that devtools starts in profile mode.
class DevtoolsStartupTest {
  const DevtoolsStartupTest(this.testDirectory);

  final String testDirectory;

  Future<TaskResult> run() async {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;

      section('Building application');
824
      String? applicationBinaryPath;
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
      switch (deviceOperatingSystem) {
        case DeviceOperatingSystem.android:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm,android-arm64',
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
          break;
        case DeviceOperatingSystem.androidArm:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm',
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
          break;
        case DeviceOperatingSystem.androidArm64:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm64',
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
          break;
        case DeviceOperatingSystem.ios:
          await flutter('build', options: <String>[
            'ios',
             '-v',
            '--profile',
          ]);
859
          applicationBinaryPath = _findDarwinAppInBuildDirectory('$testDirectory/build/ios/iphoneos');
860 861
          break;
        case DeviceOperatingSystem.fake:
862 863 864
        case DeviceOperatingSystem.fuchsia:
        case DeviceOperatingSystem.macos:
        case DeviceOperatingSystem.windows:
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
          break;
      }

      final Process process = await startProcess(path.join(flutterDirectory.path, 'bin', 'flutter'), <String>[
        'run',
        '--no-android-gradle-daemon',
        '--no-publish-port',
        '--verbose',
        '--profile',
        '-d',
        device.deviceId,
        if (applicationBinaryPath != null)
          '--use-application-binary=$applicationBinaryPath',
       ]);
      final Completer<void> completer = Completer<void>();
      bool sawLine = false;
      process.stdout
        .transform(utf8.decoder)
        .transform(const LineSplitter())
        .listen((String line) {
          print('[STDOUT]: $line');
        // Wait for devtools output.
        if (line.contains('The Flutter DevTools debugger and profiler')) {
          sawLine = true;
          completer.complete();
        }
      });
      bool didExit = false;
      unawaited(process.exitCode.whenComplete(() {
        didExit = true;
      }));
      await Future.any(<Future<void>>[completer.future, Future<void>.delayed(const Duration(minutes: 5)), process.exitCode]);
      if (!didExit) {
        process.stdin.writeln('q');
        await process.exitCode;
      }

      await flutter('install', options: <String>[
        '--uninstall-only',
        '-d',
        device.deviceId,
      ]);

908
      if (sawLine) {
909
        return TaskResult.success(null, benchmarkScoreKeys: <String>[]);
910
      }
911 912 913 914 915
      return TaskResult.failure('Did not see line "The Flutter DevTools debugger and profiler" in output');
    });
  }
}

916 917 918 919 920
/// A callback function to be used to mock the flutter drive command in PerfTests.
///
/// The `options` contains all the arguments in the `flutter drive` command in PerfTests.
typedef FlutterDriveCallback = void Function(List<String> options);

921 922 923
/// Measures application runtime performance, specifically per-frame
/// performance.
class PerfTest {
924
  const PerfTest(
925 926 927
    this.testDirectory,
    this.testTarget,
    this.timelineFileName, {
928
    this.measureCpuGpu = true,
929
    this.measureMemory = true,
930
    this.saveTraceFile = false,
931
    this.testDriver,
932 933
    this.needsFullTimeline = true,
    this.benchmarkScoreKeys,
934
    this.dartDefine = '',
935
    String? resultFilename,
936 937
    this.device,
    this.flutterDriveCallback,
938
    this.enableImpeller = false,
939
    this.timeoutSeconds,
940 941 942 943 944
  }): _resultFilename = resultFilename;

  const PerfTest.e2e(
    this.testDirectory,
    this.testTarget, {
945 946
    this.measureCpuGpu = false,
    this.measureMemory = false,
947 948 949 950 951
    this.testDriver =  'test_driver/e2e_test.dart',
    this.needsFullTimeline = false,
    this.benchmarkScoreKeys = _kCommonScoreKeys,
    this.dartDefine = '',
    String resultFilename = 'e2e_perf_summary',
952 953
    this.device,
    this.flutterDriveCallback,
954
    this.enableImpeller = false,
955
    this.timeoutSeconds,
956
  }) : saveTraceFile = false, timelineFileName = null, _resultFilename = resultFilename;
957 958

  /// The directory where the app under test is defined.
959
  final String testDirectory;
960
  /// The main entry-point file of the application, as run on the device.
961
  final String testTarget;
962
  // The prefix name of the filename such as `<timelineFileName>.timeline_summary.json`.
963
  final String? timelineFileName;
964
  String get traceFilename => '$timelineFileName.timeline';
965
  String get resultFilename => _resultFilename ?? '$timelineFileName.timeline_summary';
966
  final String? _resultFilename;
967
  /// The test file to run on the host.
968
  final String? testDriver;
969
  /// Whether to collect CPU and GPU metrics.
970
  final bool measureCpuGpu;
971 972
  /// Whether to collect memory metrics.
  final bool measureMemory;
973 974
  /// Whether to collect full timeline, meaning if `--trace-startup` flag is needed.
  final bool needsFullTimeline;
975 976
  /// Whether to save the trace timeline file `*.timeline.json`.
  final bool saveTraceFile;
977 978 979 980 981 982 983 984 985
  /// The device to test on.
  ///
  /// If null, the device is selected depending on the current environment.
  final Device? device;

  /// The function called instead of the actually `flutter drive`.
  ///
  /// If it is not `null`, `flutter drive` will not happen in the PerfTests.
  final FlutterDriveCallback? flutterDriveCallback;
986

987 988 989
  /// Whether the perf test should enable Impeller.
  final bool enableImpeller;

990 991 992
  /// Number of seconds to time out the test after, allowing debug callbacks to run.
  final int? timeoutSeconds;

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  /// The keys of the values that need to be reported.
  ///
  /// If it's `null`, then report:
  /// ```Dart
  /// <String>[
  ///   'average_frame_build_time_millis',
  ///   'worst_frame_build_time_millis',
  ///   '90th_percentile_frame_build_time_millis',
  ///   '99th_percentile_frame_build_time_millis',
  ///   'average_frame_rasterizer_time_millis',
  ///   'worst_frame_rasterizer_time_millis',
  ///   '90th_percentile_frame_rasterizer_time_millis',
  ///   '99th_percentile_frame_rasterizer_time_millis',
  ///   'average_vsync_transitions_missed',
  ///   '90th_percentile_vsync_transitions_missed',
  ///   '99th_percentile_vsync_transitions_missed',
1009 1010
  ///   if (measureCpuGpu) 'average_cpu_usage',
  ///   if (measureCpuGpu) 'average_gpu_usage',
1011 1012
  /// ]
  /// ```
1013
  final List<String>? benchmarkScoreKeys;
1014

1015 1016 1017
  /// Additional flags for `--dart-define` to control the test
  final String dartDefine;

1018
  Future<TaskResult> run() {
1019 1020 1021 1022 1023 1024
    return internalRun();
  }

  @protected
  Future<TaskResult> internalRun({
      bool cacheSkSL = false,
1025 1026
      String? existingApp,
      String? writeSkslFileName,
1027
  }) {
1028
    return inDirectory<TaskResult>(testDirectory, () async {
1029 1030 1031 1032 1033 1034 1035 1036
      late Device selectedDevice;
      if (device != null) {
        selectedDevice = device!;
      } else {
        selectedDevice = await devices.workingDevice;
      }
      await selectedDevice.unlock();
      final String deviceId = selectedDevice.deviceId;
1037 1038
      final String? localEngine = localEngineFromEnv;
      final String? localEngineSrcPath = localEngineSrcPathFromEnv;
1039

1040
      final List<String> options = <String>[
1041
        if (localEngine != null)
1042
          ...<String>['--local-engine', localEngine],
1043
        if (localEngineSrcPath != null)
1044
          ...<String>['--local-engine-src-path', localEngineSrcPath],
1045
        '--no-dds',
1046
        '--no-android-gradle-daemon',
1047
        '-v',
1048
        '--verbose-system-logs',
1049
        '--profile',
1050 1051 1052 1053 1054
        if (timeoutSeconds != null)
          ...<String>[
            '--timeout',
            timeoutSeconds.toString(),
          ],
1055 1056
        if (needsFullTimeline)
          '--trace-startup', // Enables "endless" timeline event buffering.
1057
        '-t', testTarget,
1058
        if (testDriver != null)
1059
          ...<String>['--driver', testDriver!],
1060 1061 1062 1063 1064
        if (existingApp != null)
          ...<String>['--use-existing-app', existingApp],
        if (writeSkslFileName != null)
          ...<String>['--write-sksl-on-exit', writeSkslFileName],
        if (cacheSkSL) '--cache-sksl',
1065 1066
        if (dartDefine.isNotEmpty)
          ...<String>['--dart-define', dartDefine],
1067
        if (enableImpeller) '--enable-impeller',
1068 1069
        '-d',
        deviceId,
1070 1071 1072 1073
      ];
      if (flutterDriveCallback != null) {
        flutterDriveCallback!(options);
      } else {
1074
        await flutter('drive', options: options);
1075
      }
1076
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
1077
        file('${_testOutputDirectory(testDirectory)}/$resultFilename.json').readAsStringSync(),
1078
      ) as Map<String, dynamic>;
1079

1080
      if (data['frame_count'] as int < 5) {
1081
        return TaskResult.failure(
1082 1083 1084 1085 1086
          'Timeline contains too few frames: ${data['frame_count']}. Possibly '
          'trace events are not being captured.',
        );
      }

1087 1088 1089
      // TODO(liyuqian): Remove isAndroid restriction once
      // https://github.com/flutter/flutter/issues/61567 is fixed.
      final bool isAndroid = deviceOperatingSystem == DeviceOperatingSystem.android;
1090 1091
      return TaskResult.success(
        data,
1092 1093
        detailFiles: <String>[
          if (saveTraceFile)
Dan Field's avatar
Dan Field committed
1094
            '${_testOutputDirectory(testDirectory)}/$traceFilename.json',
1095
        ],
1096
        benchmarkScoreKeys: benchmarkScoreKeys ?? <String>[
1097
          ..._kCommonScoreKeys,
1098 1099 1100
          'average_vsync_transitions_missed',
          '90th_percentile_vsync_transitions_missed',
          '99th_percentile_vsync_transitions_missed',
1101
          if (measureCpuGpu && !isAndroid) ...<String>[
1102 1103 1104
            // See https://github.com/flutter/flutter/issues/68888
            if (data['average_cpu_usage'] != null) 'average_cpu_usage',
            if (data['average_gpu_usage'] != null) 'average_gpu_usage',
1105 1106
          ],
          if (measureMemory && !isAndroid) ...<String>[
1107 1108
            // See https://github.com/flutter/flutter/issues/68888
            if (data['average_memory_usage'] != null) 'average_memory_usage',
1109 1110
            if (data['90th_percentile_memory_usage'] != null) '90th_percentile_memory_usage',
            if (data['99th_percentile_memory_usage'] != null) '99th_percentile_memory_usage',
1111
          ],
1112 1113 1114 1115 1116 1117
          if (data['30hz_frame_percentage'] != null) '30hz_frame_percentage',
          if (data['60hz_frame_percentage'] != null) '60hz_frame_percentage',
          if (data['80hz_frame_percentage'] != null) '80hz_frame_percentage',
          if (data['90hz_frame_percentage'] != null) '90hz_frame_percentage',
          if (data['120hz_frame_percentage'] != null) '120hz_frame_percentage',
          if (data['illegal_refresh_rate_frame_count'] != null) 'illegal_refresh_rate_frame_count',
1118 1119
        ],
      );
1120 1121 1122 1123
    });
  }
}

1124 1125 1126 1127 1128 1129 1130 1131 1132
const List<String> _kCommonScoreKeys = <String>[
  'average_frame_build_time_millis',
  'worst_frame_build_time_millis',
  '90th_percentile_frame_build_time_millis',
  '99th_percentile_frame_build_time_millis',
  'average_frame_rasterizer_time_millis',
  'worst_frame_rasterizer_time_millis',
  '90th_percentile_frame_rasterizer_time_millis',
  '99th_percentile_frame_rasterizer_time_millis',
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
  'average_layer_cache_count',
  '90th_percentile_layer_cache_count',
  '99th_percentile_layer_cache_count',
  'worst_layer_cache_count',
  'average_layer_cache_memory',
  '90th_percentile_layer_cache_memory',
  '99th_percentile_layer_cache_memory',
  'worst_layer_cache_memory',
  'average_picture_cache_count',
  '90th_percentile_picture_cache_count',
  '99th_percentile_picture_cache_count',
  'worst_picture_cache_count',
  'average_picture_cache_memory',
  '90th_percentile_picture_cache_memory',
  '99th_percentile_picture_cache_memory',
  'worst_picture_cache_memory',
1149 1150
  'new_gen_gc_count',
  'old_gen_gc_count',
1151
];
1152

1153 1154
class PerfTestWithSkSL extends PerfTest {
  PerfTestWithSkSL(
1155 1156 1157 1158 1159 1160 1161 1162
    super.testDirectory,
    super.testTarget,
    String super.timelineFileName, {
    super.measureCpuGpu = false,
    super.testDriver,
    super.needsFullTimeline,
    super.benchmarkScoreKeys,
  });
1163 1164 1165


  PerfTestWithSkSL.e2e(
1166 1167 1168 1169
    super.testDirectory,
    super.testTarget, {
    String super.testDriver,
    super.resultFilename,
1170 1171
  }) : super.e2e(
    needsFullTimeline: false,
1172 1173 1174
  );

  @override
1175
  Future<TaskResult> run({int? timeoutSeconds}) async {
1176 1177 1178 1179 1180 1181 1182 1183 1184
    return inDirectory<TaskResult>(testDirectory, () async {
      // Some initializations
      _device = await devices.workingDevice;
      _flutterPath = path.join(flutterDirectory.path, 'bin', 'flutter');

      // Prepare the SkSL by running the driver test.
      await _generateSkSL();

      // Build the app with SkSL artifacts and run that app
1185
      final String observatoryUri = await _runApp(skslPath: _skslJsonFileName);
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

      // Attach to the running app and run the final driver test to get metrics.
      final TaskResult result = await internalRun(
        existingApp: observatoryUri,
      );

      _runProcess.kill();
      await _runProcess.exitCode;

      return result;
    });
  }

  Future<void> _generateSkSL() async {
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
    // `flutter drive` without `flutter run`, and `flutter drive --existing-app`
    // with `flutter run` may generate different SkSLs. Hence we run both
    // versions to generate as many SkSLs as possible.
    //
    // 1st, `flutter drive --existing-app` with `flutter run`. The
    // `--write-sksl-on-exit` option doesn't seem to be compatible with
    // `flutter drive --existing-app` as it will complain web socket connection
    // issues.
    final String observatoryUri = await _runApp(cacheSkSL: true);
    await super.internalRun(cacheSkSL: true, existingApp: observatoryUri);
    _runProcess.kill();
    await _runProcess.exitCode;

    // 2nd, `flutter drive` without `flutter run`. The --no-build option ensures
    // that we won't remove the SkSLs generated earlier.
1215 1216 1217 1218 1219 1220
    await super.internalRun(
      cacheSkSL: true,
      writeSkslFileName: _skslJsonFileName,
    );
  }

1221
  Future<String> _runApp({String? appBinary, bool cacheSkSL = false, String? skslPath}) async {
1222 1223 1224
    if (File(_vmserviceFileName).existsSync()) {
      File(_vmserviceFileName).deleteSync();
    }
1225 1226
    final String? localEngine = localEngineFromEnv;
    final String? localEngineSrcPath = localEngineSrcPathFromEnv;
1227 1228 1229 1230
    _runProcess = await startProcess(
      _flutterPath,
      <String>[
        'run',
1231
        if (localEngine != null)
1232
          ...<String>['--local-engine', localEngine],
1233
        if (localEngineSrcPath != null)
1234
          ...<String>['--local-engine-src-path', localEngineSrcPath],
1235
        '--no-dds',
1236 1237
        if (deviceOperatingSystem == DeviceOperatingSystem.ios)
          ...<String>[
1238
            '--device-timeout', '5',
1239
          ],
1240
        '--verbose',
1241
        '--verbose-system-logs',
1242
        '--purge-persistent-cache',
1243
        '--no-publish-port',
1244
        '--profile',
1245
        if (skslPath != null) '--bundle-sksl-path=$skslPath',
1246
        if (cacheSkSL) '--cache-sksl',
1247 1248 1249
        '-d', _device.deviceId,
        '-t', testTarget,
        '--endless-trace-buffer',
1250
        if (appBinary != null) ...<String>['--use-application-binary', _appBinary],
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
        '--vmservice-out-file', _vmserviceFileName,
      ],
    );

    final Stream<List<int>> broadcastOut = _runProcess.stdout.asBroadcastStream();
    _forwardStream(broadcastOut, 'run stdout');
    _forwardStream(_runProcess.stderr, 'run stderr');

    final File file = await waitForFile(_vmserviceFileName);
    return file.readAsStringSync();
  }

  String get _skslJsonFileName => '$testDirectory/flutter_01.sksl.json';
  String get _vmserviceFileName => '$testDirectory/$_kVmserviceOutFileName';

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
  bool get _isAndroid => deviceOperatingSystem == DeviceOperatingSystem.android;

  String get _appBinary {
    if (_isAndroid) {
      return '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
    }
    for (final FileSystemEntity entry in Directory('$testDirectory/build/ios/iphoneos/').listSync()) {
      if (entry.path.endsWith('.app')) {
        return entry.path;
      }
    }
    throw 'No app found.';
  }

1280 1281 1282 1283 1284 1285 1286 1287 1288
  Stream<String> _transform(Stream<List<int>> stream) =>
      stream.transform<String>(utf8.decoder).transform<String>(const LineSplitter());

  void _forwardStream(Stream<List<int>> stream, String label) {
    _transform(stream).listen((String line) {
      print('$label: $line');
    });
  }

1289 1290 1291
  late String _flutterPath;
  late Device _device;
  late Process _runProcess;
1292 1293 1294 1295

  static const String _kVmserviceOutFileName = 'vmservice.out';
}

1296 1297 1298 1299 1300 1301 1302
/// Measures how long it takes to compile a Flutter app to JavaScript and how
/// big the compiled code is.
class WebCompileTest {
  const WebCompileTest();

  Future<TaskResult> run() async {
    final Map<String, Object> metrics = <String, Object>{};
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

    metrics.addAll(await runSingleBuildTest(
      directory: '${flutterDirectory.path}/examples/hello_world',
      metric: 'hello_world',
    ));

    metrics.addAll(await runSingleBuildTest(
      directory: '${flutterDirectory.path}/dev/integration_tests/flutter_gallery',
      metric: 'flutter_gallery',
    ));

    const String sampleAppName = 'sample_flutter_app';
    final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName');

    rmTree(sampleDir);

    await inDirectory<void>(Directory.systemTemp, () async {
1320
      await flutter('create', options: <String>['--template=app', sampleAppName]);
1321
    });
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334

    metrics.addAll(await runSingleBuildTest(
      directory: sampleDir.path,
      metric: 'basic_material_app',
    ));

    return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
  }

  /// Run a single web compile test and return its metrics.
  ///
  /// Run a single web compile test for the app under [directory], and store
  /// its metrics with prefix [metric].
1335 1336 1337 1338 1339
  static Future<Map<String, int>> runSingleBuildTest({
    required String directory,
    required String metric,
    bool measureBuildTime = false,
  }) {
1340 1341 1342
    return inDirectory<Map<String, int>>(directory, () async {
      final Map<String, int> metrics = <String, int>{};

1343
      await flutter('packages', options: <String>['get']);
1344
      final Stopwatch? watch = measureBuildTime ? Stopwatch() : null;
1345
      watch?.start();
1346 1347 1348 1349 1350
      await evalFlutter('build', options: <String>[
        'web',
        '-v',
        '--release',
        '--no-pub',
1351
      ]);
1352
      watch?.stop();
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
      final String buildDir = path.join(directory, 'build', 'web');
      metrics.addAll(await getSize(
        directories: <String, String>{'web_build_dir': buildDir},
        files: <String, String>{
          'dart2js': path.join(buildDir, 'main.dart.js'),
          'canvaskit_wasm': path.join(buildDir, 'canvaskit', 'canvaskit.wasm'),
          'canvaskit_js': path.join(buildDir, 'canvaskit', 'canvaskit.js'),
          'flutter_js': path.join(buildDir, 'flutter.js'),
        },
        metric: metric,
      ));
1364

1365
      if (measureBuildTime) {
1366
        metrics['${metric}_dart2js_millis'] = watch!.elapsedMilliseconds;
1367
      }
1368

1369
      return metrics;
1370 1371 1372
    });
  }

1373 1374 1375 1376 1377 1378 1379 1380 1381
  /// Obtains the size and gzipped size of both [dartBundleFile] and [buildDir].
  static Future<Map<String, int>> getSize({
    /// Mapping of metric key name to file system path for directories to measure
    Map<String, String> directories = const <String, String>{},
    /// Mapping of metric key name to file system path for files to measure
    Map<String, String> files = const <String, String>{},
    required String metric,
  }) async {
    const String kGzipCompressionLevel = '-9';
1382 1383
    final Map<String, int> sizeMetrics = <String, int>{};

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    final Directory tempDir = Directory.systemTemp.createTempSync('perf_tests_gzips');
    try {
      for (final MapEntry<String, String> entry in files.entries) {
        final String key = entry.key;
        final String filePath = entry.value;
        sizeMetrics['${metric}_${key}_uncompressed_bytes'] = File(filePath).lengthSync();

        await Process.run('gzip',<String>['--keep', kGzipCompressionLevel, filePath]);
        // gzip does not provide a CLI option to specify an output file, so
        // instead just move the output file to the temp dir
        final File compressedFile = File('$filePath.gz')
            .renameSync(path.join(tempDir.absolute.path, '$key.gz'));
        sizeMetrics['${metric}_${key}_compressed_bytes'] = compressedFile.lengthSync();
      }
1398

1399 1400 1401
      for (final MapEntry<String, String> entry in directories.entries) {
        final String key = entry.key;
        final String dirPath = entry.value;
1402

1403 1404 1405 1406 1407 1408 1409 1410
        final String tarball = path.join(tempDir.absolute.path, '$key.tar');
        await Process.run('tar', <String>[
          '--create',
          '--verbose',
          '--file=$tarball',
          dirPath,
        ]);
        sizeMetrics['${metric}_${key}_uncompressed_bytes'] = File(tarball).lengthSync();
1411

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
        // get size of compressed build directory
        await Process.run('gzip',<String>['--keep', kGzipCompressionLevel, tarball]);
        sizeMetrics['${metric}_${key}_compressed_bytes'] = File('$tarball.gz').lengthSync();
      }
    } finally {
      try {
        tempDir.deleteSync(recursive: true);
      } on FileSystemException {
        print('Failed to delete ${tempDir.path}.');
      }
    }
    return sizeMetrics;
1424 1425 1426
  }
}

1427
/// Measures how long it takes to compile a Flutter app and how big the compiled
1428
/// code is.
1429
class CompileTest {
1430
  const CompileTest(this.testDirectory, { this.reportPackageContentSizes = false });
1431 1432

  final String testDirectory;
1433
  final bool reportPackageContentSizes;
1434

1435
  Future<TaskResult> run() async {
1436
    return inDirectory<TaskResult>(testDirectory, () async {
1437
      await flutter('packages', options: <String>['get']);
1438

1439 1440 1441 1442 1443
      // "initial" compile required downloading and creating the `android/.gradle` directory while "full"
      // compiles only run `flutter clean` between runs.
      final Map<String, dynamic> compileInitialRelease = await _compileApp(deleteGradleCache: true);
      final Map<String, dynamic> compileFullRelease = await _compileApp(deleteGradleCache: false);
      final Map<String, dynamic> compileInitialDebug = await _compileDebug(
1444
        clean: true,
1445 1446 1447 1448 1449 1450
        deleteGradleCache: true,
        metricKey: 'debug_initial_compile_millis',
      );
      final Map<String, dynamic> compileFullDebug = await _compileDebug(
        clean: true,
        deleteGradleCache: false,
1451 1452 1453 1454 1455
        metricKey: 'debug_full_compile_millis',
      );
      // Build again without cleaning, should be faster.
      final Map<String, dynamic> compileSecondDebug = await _compileDebug(
        clean: false,
1456
        deleteGradleCache: false,
1457 1458 1459
        metricKey: 'debug_second_compile_millis',
      );

1460
      final Map<String, dynamic> metrics = <String, dynamic>{
1461 1462 1463 1464
        ...compileInitialRelease,
        ...compileFullRelease,
        ...compileInitialDebug,
        ...compileFullDebug,
1465
        ...compileSecondDebug,
1466
      };
1467

1468 1469 1470 1471 1472 1473 1474 1475
      final File mainDart = File('$testDirectory/lib/main.dart');
      if (mainDart.existsSync()) {
        final List<int> bytes = mainDart.readAsBytesSync();
        // "Touch" the file
        mainDart.writeAsStringSync(' ', mode: FileMode.append, flush: true);
        // Build after "edit" without clean should be faster than first build
        final Map<String, dynamic> compileAfterEditDebug = await _compileDebug(
          clean: false,
1476
          deleteGradleCache: false,
1477 1478 1479 1480 1481 1482 1483
          metricKey: 'debug_compile_after_edit_millis',
        );
        metrics.addAll(compileAfterEditDebug);
        // Revert the changes
        mainDart.writeAsBytesSync(bytes, flush: true);
      }

1484
      return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
1485 1486
    });
  }
1487

1488
  Future<Map<String, dynamic>> _compileApp({required bool deleteGradleCache}) async {
1489
    await flutter('clean');
1490 1491 1492 1493
    if (deleteGradleCache) {
      final Directory gradleCacheDir = Directory('$testDirectory/android/.gradle');
      rmTree(gradleCacheDir);
    }
1494
    final Stopwatch watch = Stopwatch();
1495 1496
    int releaseSizeInBytes;
    final List<String> options = <String>['--release'];
1497 1498
    final Map<String, dynamic> metrics = <String, dynamic>{};

Ian Hickson's avatar
Ian Hickson committed
1499 1500
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
      case DeviceOperatingSystem.macos:
        unawaited(stderr.flush());
        late final String deviceId;
        if (deviceOperatingSystem == DeviceOperatingSystem.ios) {
          deviceId = 'ios';
        } else if (deviceOperatingSystem == DeviceOperatingSystem.macos) {
          deviceId = 'macos';
        } else {
          throw Exception('Attempted to run darwin compile workflow with $deviceOperatingSystem');
        }

        options.insert(0, deviceId);
1513 1514
        options.add('--tree-shake-icons');
        options.add('--split-debug-info=infos/');
Ian Hickson's avatar
Ian Hickson committed
1515 1516 1517
        watch.start();
        await flutter('build', options: options);
        watch.stop();
1518 1519 1520 1521
        final Directory buildDirectory = dir(path.join(
          cwd,
          'build',
        ));
1522
        final String? appPath =
1523
            _findDarwinAppInBuildDirectory(buildDirectory.path);
1524
        if (appPath == null) {
1525
          throw 'Failed to find app bundle in ${buildDirectory.path}';
1526
        }
1527 1528 1529 1530
        // Validate changes in Dart snapshot format and data layout do not
        // change compression size. This also simulates the size of an IPA on iOS.
        await exec('tar', <String>['-zcf', 'build/app.tar.gz', appPath]);
        releaseSizeInBytes = await file('$cwd/build/app.tar.gz').length();
1531
        if (reportPackageContentSizes) {
1532
          final Map<String, Object> sizeMetrics = await getSizesFromDarwinApp(
1533 1534
            appPath: appPath,
            operatingSystem: deviceOperatingSystem,
1535 1536
          );
          metrics.addAll(sizeMetrics);
1537
        }
Ian Hickson's avatar
Ian Hickson committed
1538 1539
        break;
      case DeviceOperatingSystem.android:
1540
      case DeviceOperatingSystem.androidArm:
Ian Hickson's avatar
Ian Hickson committed
1541
        options.insert(0, 'apk');
1542
        options.add('--target-platform=android-arm');
1543
        options.add('--tree-shake-icons');
1544
        options.add('--split-debug-info=infos/');
Ian Hickson's avatar
Ian Hickson committed
1545 1546 1547
        watch.start();
        await flutter('build', options: options);
        watch.stop();
1548 1549
        final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk';
        final File apk = file(apkPath);
1550
        releaseSizeInBytes = apk.lengthSync();
1551
        if (reportPackageContentSizes) {
1552
          metrics.addAll(await getSizesFromApk(apkPath));
1553
        }
Ian Hickson's avatar
Ian Hickson committed
1554
        break;
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
      case DeviceOperatingSystem.androidArm64:
        options.insert(0, 'apk');
        options.add('--target-platform=android-arm64');
        options.add('--tree-shake-icons');
        options.add('--split-debug-info=infos/');
        watch.start();
        await flutter('build', options: options);
        watch.stop();
        final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk';
        final File apk = file(apkPath);
        releaseSizeInBytes = apk.lengthSync();
1566
        if (reportPackageContentSizes) {
1567
          metrics.addAll(await getSizesFromApk(apkPath));
1568
        }
1569
        break;
1570 1571
      case DeviceOperatingSystem.fake:
        throw Exception('Unsupported option for fake devices');
1572 1573 1574
      case DeviceOperatingSystem.fuchsia:
        throw Exception('Unsupported option for Fuchsia devices');
      case DeviceOperatingSystem.windows:
1575 1576 1577 1578 1579 1580 1581
        unawaited(stderr.flush());
        options.insert(0, 'windows');
        options.add('--tree-shake-icons');
        options.add('--split-debug-info=infos/');
        watch.start();
        await flutter('build', options: options);
        watch.stop();
1582 1583
        final String basename = path.basename(cwd);
        final String exePath = path.join(
1584 1585 1586 1587 1588
          cwd,
          'build',
          'windows',
          'runner',
          'release',
1589 1590
          '$basename.exe');
        final File exe = file(exePath);
1591
        // On Windows, we do not produce a single installation package file,
1592 1593 1594
        // rather a directory containing an .exe and .dll files.
        // The release size is set to the size of the produced .exe file
        releaseSizeInBytes = exe.lengthSync();
1595
        break;
1596
    }
1597

1598
    metrics.addAll(<String, dynamic>{
1599
      'release_${deleteGradleCache ? 'initial' : 'full'}_compile_millis': watch.elapsedMilliseconds,
1600
      'release_size_bytes': releaseSizeInBytes,
1601 1602 1603
    });

    return metrics;
1604 1605
  }

1606 1607
  Future<Map<String, dynamic>> _compileDebug({
    required bool deleteGradleCache,
1608 1609
    required bool clean,
    required String metricKey,
1610 1611 1612 1613
  }) async {
    if (clean) {
      await flutter('clean');
    }
1614 1615 1616 1617
    if (deleteGradleCache) {
      final Directory gradleCacheDir = Directory('$testDirectory/android/.gradle');
      rmTree(gradleCacheDir);
    }
1618
    final Stopwatch watch = Stopwatch();
Ian Hickson's avatar
Ian Hickson committed
1619 1620 1621 1622 1623 1624
    final List<String> options = <String>['--debug'];
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.insert(0, 'ios');
        break;
      case DeviceOperatingSystem.android:
1625
      case DeviceOperatingSystem.androidArm:
Ian Hickson's avatar
Ian Hickson committed
1626
        options.insert(0, 'apk');
1627
        options.add('--target-platform=android-arm');
Ian Hickson's avatar
Ian Hickson committed
1628
        break;
1629 1630 1631 1632
      case DeviceOperatingSystem.androidArm64:
        options.insert(0, 'apk');
        options.add('--target-platform=android-arm64');
        break;
1633 1634
      case DeviceOperatingSystem.fake:
        throw Exception('Unsupported option for fake devices');
1635 1636 1637
      case DeviceOperatingSystem.fuchsia:
        throw Exception('Unsupported option for Fuchsia devices');
      case DeviceOperatingSystem.macos:
1638 1639 1640
        unawaited(stderr.flush());
        options.insert(0, 'macos');
        break;
1641
      case DeviceOperatingSystem.windows:
1642 1643 1644
        unawaited(stderr.flush());
        options.insert(0, 'windows');
        break;
1645
    }
Ian Hickson's avatar
Ian Hickson committed
1646 1647 1648
    watch.start();
    await flutter('build', options: options);
    watch.stop();
1649 1650

    return <String, dynamic>{
1651
      metricKey: watch.elapsedMilliseconds,
1652 1653 1654
    };
  }

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
  static Future<Map<String, Object>> getSizesFromDarwinApp({
    required String appPath,
    required DeviceOperatingSystem operatingSystem,
  }) async {
    late final File flutterFramework;
    late final String frameworkDirectory;
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        frameworkDirectory = path.join(
          appPath,
          'Frameworks',
        );
        flutterFramework = File(path.join(
          frameworkDirectory,
          'Flutter.framework',
          'Flutter',
        ));
        break;
      case DeviceOperatingSystem.macos:
        frameworkDirectory = path.join(
          appPath,
          'Contents',
          'Frameworks',
        );
        flutterFramework = File(path.join(
          frameworkDirectory,
          'FlutterMacOS.framework',
          'FlutterMacOS',
        )); // https://github.com/flutter/flutter/issues/70413
        break;
      case DeviceOperatingSystem.android:
      case DeviceOperatingSystem.androidArm:
      case DeviceOperatingSystem.androidArm64:
      case DeviceOperatingSystem.fake:
      case DeviceOperatingSystem.fuchsia:
      case DeviceOperatingSystem.windows:
        throw Exception('Called ${CompileTest.getSizesFromDarwinApp} with $operatingSystem.');
    }
1693

1694 1695 1696 1697 1698
    final File appFramework = File(path.join(
      frameworkDirectory,
      'App.framework',
      'App',
    ));
1699

1700
    return <String, Object>{
1701 1702 1703 1704 1705
      'app_framework_uncompressed_bytes': await appFramework.length(),
      'flutter_framework_uncompressed_bytes': await flutterFramework.length(),
    };
  }

1706 1707 1708 1709 1710 1711 1712
  static Future<Map<String, dynamic>> getSizesFromApk(String apkPath) async {
    final  String output = await eval('unzip', <String>['-v', apkPath]);
    final List<String> lines = output.split('\n');
    final Map<String, _UnzipListEntry> fileToMetadata = <String, _UnzipListEntry>{};

    // First three lines are header, last two lines are footer.
    for (int i = 3; i < lines.length - 2; i++) {
1713
      final _UnzipListEntry entry = _UnzipListEntry.fromLine(lines[i]);
1714 1715 1716
      fileToMetadata[entry.path] = entry;
    }

1717 1718 1719
    final _UnzipListEntry libflutter = fileToMetadata['lib/armeabi-v7a/libflutter.so']!;
    final _UnzipListEntry libapp = fileToMetadata['lib/armeabi-v7a/libapp.so']!;
    final _UnzipListEntry license = fileToMetadata['assets/flutter_assets/NOTICES.Z']!;
1720 1721 1722 1723

    return <String, dynamic>{
      'libflutter_uncompressed_bytes': libflutter.uncompressedSize,
      'libflutter_compressed_bytes': libflutter.compressedSize,
1724 1725
      'libapp_uncompressed_bytes': libapp.uncompressedSize,
      'libapp_compressed_bytes': libapp.compressedSize,
1726 1727
      'license_uncompressed_bytes': license.uncompressedSize,
      'license_compressed_bytes': license.compressedSize,
1728 1729
    };
  }
1730
}
1731

1732
/// Measure application memory usage.
1733
class MemoryTest {
1734 1735 1736 1737 1738 1739 1740 1741
  MemoryTest(this.project, this.test, this.package);

  final String project;
  final String test;
  final String package;

  /// Completes when the log line specified in the last call to
  /// [prepareForNextMessage] is seen by `adb logcat`.
1742 1743 1744
  Future<void>? get receivedNextMessage => _receivedNextMessage?.future;
  Completer<void>? _receivedNextMessage;
  String? _nextMessage;
1745 1746 1747 1748 1749

  /// Prepares the [receivedNextMessage] future such that it will complete
  /// when `adb logcat` sees a log line with the given `message`.
  void prepareForNextMessage(String message) {
    _nextMessage = message;
1750
    _receivedNextMessage = Completer<void>();
1751
  }
1752

1753
  int get iterationCount => 10;
1754

1755 1756
  Device? get device => _device;
  Device? _device;
1757

1758
  Future<TaskResult> run() {
1759
    return inDirectory<TaskResult>(project, () async {
1760 1761 1762 1763
      // This test currently only works on Android, because device.logcat,
      // device.getMemoryStats, etc, aren't implemented for iOS.

      _device = await devices.workingDevice;
1764
      await device!.unlock();
1765 1766
      await flutter('packages', options: <String>['get']);

1767
      final StreamSubscription<String> adb = device!.logcat.listen(
1768
        (String data) {
1769
          if (data.contains('==== MEMORY BENCHMARK ==== $_nextMessage ====')) {
1770
            _receivedNextMessage?.complete();
1771
          }
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
        },
      );

      for (int iteration = 0; iteration < iterationCount; iteration += 1) {
        print('running memory test iteration $iteration...');
        _startMemoryUsage = null;
        await useMemory();
        assert(_startMemoryUsage != null);
        assert(_startMemory.length == iteration + 1);
        assert(_endMemory.length == iteration + 1);
        assert(_diffMemory.length == iteration + 1);
        print('terminating...');
1784
        await device!.stop(package);
1785
        await Future<void>.delayed(const Duration(milliseconds: 10));
1786
      }
1787

1788
      await adb.cancel();
1789
      await flutter('install', options: <String>['--uninstall-only', '-d', device!.deviceId]);
1790

1791 1792 1793
      final ListStatistics startMemoryStatistics = ListStatistics(_startMemory);
      final ListStatistics endMemoryStatistics = ListStatistics(_endMemory);
      final ListStatistics diffMemoryStatistics = ListStatistics(_diffMemory);
1794

1795 1796 1797 1798 1799
      final Map<String, dynamic> memoryUsage = <String, dynamic>{
        ...startMemoryStatistics.asMap('start'),
        ...endMemoryStatistics.asMap('end'),
        ...diffMemoryStatistics.asMap('diff'),
      };
1800

1801 1802 1803 1804 1805
      _device = null;
      _startMemory.clear();
      _endMemory.clear();
      _diffMemory.clear();

1806
      return TaskResult.success(memoryUsage, benchmarkScoreKeys: memoryUsage.keys.toList());
1807 1808
    });
  }
1809

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
  /// Starts the app specified by [test] on the [device].
  ///
  /// The [run] method will terminate it by its package name ([package]).
  Future<void> launchApp() async {
    prepareForNextMessage('READY');
    print('launching $project$test on device...');
    await flutter('run', options: <String>[
      '--verbose',
      '--release',
      '--no-resident',
1820
      '-d', device!.deviceId,
1821 1822 1823 1824 1825
      test,
    ]);
    print('awaiting "ready" message...');
    await receivedNextMessage;
  }
1826

1827
  /// To change the behavior of the test, override this.
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
  ///
  /// Make sure to call recordStart() and recordEnd() once each in that order.
  ///
  /// By default it just launches the app, records memory usage, taps the device,
  /// awaits a DONE notification, and records memory usage again.
  Future<void> useMemory() async {
    await launchApp();
    await recordStart();

    prepareForNextMessage('DONE');
    print('tapping device...');
1839
    await device!.tap(100, 100);
1840 1841 1842 1843 1844
    print('awaiting "done" message...');
    await receivedNextMessage;

    await recordEnd();
  }
1845

1846 1847 1848
  final List<int> _startMemory = <int>[];
  final List<int> _endMemory = <int>[];
  final List<int> _diffMemory = <int>[];
1849

1850
  Map<String, dynamic>? _startMemoryUsage;
1851

1852 1853 1854 1855
  @protected
  Future<void> recordStart() async {
    assert(_startMemoryUsage == null);
    print('snapshotting memory usage...');
1856
    _startMemoryUsage = await device!.getMemoryStats(package);
1857
  }
1858

1859 1860 1861 1862
  @protected
  Future<void> recordEnd() async {
    assert(_startMemoryUsage != null);
    print('snapshotting memory usage...');
1863 1864
    final Map<String, dynamic> endMemoryUsage = await device!.getMemoryStats(package);
    _startMemory.add(_startMemoryUsage!['total_kb'] as int);
1865
    _endMemory.add(endMemoryUsage['total_kb'] as int);
1866
    _diffMemory.add((endMemoryUsage['total_kb'] as int) - (_startMemoryUsage!['total_kb'] as int));
1867 1868
  }
}
1869

1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
class DevToolsMemoryTest {
  DevToolsMemoryTest(this.project, this.driverTest);

  final String project;
  final String driverTest;

  Future<TaskResult> run() {
    return inDirectory<TaskResult>(project, () async {
      _device = await devices.workingDevice;
      await _device.unlock();

      await flutter(
        'drive',
        options: <String>[
          '-d', _device.deviceId,
          '--profile',
1886 1887 1888
          '--profile-memory', _kJsonFileName,
          '--no-publish-port',
          '-v',
1889 1890 1891 1892 1893 1894 1895
          driverTest,
        ],
      );

      final Map<String, dynamic> data = json.decode(
        file('$project/$_kJsonFileName').readAsStringSync(),
      ) as Map<String, dynamic>;
1896
      final List<dynamic> samples = (data['samples'] as Map<String, dynamic>)['data'] as List<dynamic>;
1897 1898
      int maxRss = 0;
      int maxAdbTotal = 0;
1899
      for (final Map<String, dynamic> sample in samples.cast<Map<String, dynamic>>()) {
1900 1901 1902
        if (sample['rss'] != null) {
          maxRss = math.max(maxRss, sample['rss'] as int);
        }
1903
        if (sample['adb_memoryInfo'] != null) {
1904
          maxAdbTotal = math.max(maxAdbTotal, (sample['adb_memoryInfo'] as Map<String, dynamic>)['Total'] as int);
1905 1906
        }
      }
1907

1908
      return TaskResult.success(
1909 1910
        <String, dynamic>{'maxRss': maxRss, 'maxAdbTotal': maxAdbTotal},
        benchmarkScoreKeys: <String>['maxRss', 'maxAdbTotal'],
1911 1912 1913 1914
      );
    });
  }

1915
  late Device _device;
1916 1917 1918 1919

  static const String _kJsonFileName = 'devtools_memory.json';
}

1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
enum ReportedDurationTestFlavor {
  debug, profile, release
}

String _reportedDurationTestToString(ReportedDurationTestFlavor flavor) {
  switch (flavor) {
    case ReportedDurationTestFlavor.debug:
      return 'debug';
    case ReportedDurationTestFlavor.profile:
      return 'profile';
    case ReportedDurationTestFlavor.release:
      return 'release';
  }
}

1935
class ReportedDurationTest {
1936
  ReportedDurationTest(this.flavor, this.project, this.test, this.package, this.durationPattern);
1937

1938
  final ReportedDurationTestFlavor flavor;
1939 1940 1941 1942 1943 1944 1945 1946 1947
  final String project;
  final String test;
  final String package;
  final RegExp durationPattern;

  final Completer<int> durationCompleter = Completer<int>();

  int get iterationCount => 10;

1948 1949
  Device? get device => _device;
  Device? _device;
1950 1951 1952 1953 1954 1955 1956

  Future<TaskResult> run() {
    return inDirectory<TaskResult>(project, () async {
      // This test currently only works on Android, because device.logcat,
      // device.getMemoryStats, etc, aren't implemented for iOS.

      _device = await devices.workingDevice;
1957
      await device!.unlock();
1958 1959
      await flutter('packages', options: <String>['get']);

1960
      final StreamSubscription<String> adb = device!.logcat.listen(
1961
        (String data) {
1962
          if (durationPattern.hasMatch(data)) {
1963
            durationCompleter.complete(int.parse(durationPattern.firstMatch(data)!.group(1)!));
1964
          }
1965 1966 1967 1968 1969
        },
      );
      print('launching $project$test on device...');
      await flutter('run', options: <String>[
        '--verbose',
1970
        '--no-publish-port',
1971
        '--no-fast-start',
1972
        '--${_reportedDurationTestToString(flavor)}',
1973
        '--no-resident',
1974
        '-d', device!.deviceId,
1975 1976 1977 1978 1979
        test,
      ]);

      final int duration = await durationCompleter.future;
      print('terminating...');
1980
      await device!.stop(package);
1981 1982 1983 1984 1985
      await adb.cancel();

      _device = null;

      final Map<String, dynamic> reportedDuration = <String, dynamic>{
1986
        'duration': duration,
1987 1988 1989 1990 1991 1992 1993 1994
      };
      _device = null;

      return TaskResult.success(reportedDuration, benchmarkScoreKeys: reportedDuration.keys.toList());
    });
  }
}

1995 1996 1997 1998
/// Holds simple statistics of an odd-lengthed list of integers.
class ListStatistics {
  factory ListStatistics(Iterable<int> data) {
    assert(data.isNotEmpty);
1999
    assert(data.length.isOdd);
2000
    final List<int> sortedData = data.toList()..sort();
2001
    return ListStatistics._(
2002 2003 2004 2005 2006
      sortedData.first,
      sortedData.last,
      sortedData[(sortedData.length - 1) ~/ 2],
    );
  }
2007

2008
  const ListStatistics._(this.min, this.max, this.median);
2009

2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
  final int min;
  final int max;
  final int median;

  Map<String, int> asMap(String prefix) {
    return <String, int>{
      '$prefix-min': min,
      '$prefix-max': max,
      '$prefix-median': median,
    };
2020 2021
  }
}
2022 2023 2024

class _UnzipListEntry {
  factory _UnzipListEntry.fromLine(String line) {
2025
    final List<String> data = line.trim().split(RegExp(r'\s+'));
2026
    assert(data.length == 8);
2027
    return _UnzipListEntry._(
2028 2029 2030 2031 2032 2033 2034
      uncompressedSize:  int.parse(data[0]),
      compressedSize: int.parse(data[2]),
      path: data[7],
    );
  }

  _UnzipListEntry._({
2035 2036 2037
    required this.uncompressedSize,
    required this.compressedSize,
    required this.path,
2038 2039 2040 2041 2042 2043 2044 2045 2046
  }) : assert(uncompressedSize != null),
       assert(compressedSize != null),
       assert(compressedSize <= uncompressedSize),
       assert(path != null);

  final int uncompressedSize;
  final int compressedSize;
  final String path;
}
2047

2048
/// Wait for up to 1 hour for the file to appear.
2049
Future<File> waitForFile(String path) async {
2050
  for (int i = 0; i < 180; i += 1) {
2051 2052 2053 2054 2055 2056 2057
    final File file = File(path);
    print('looking for ${file.path}');
    if (file.existsSync()) {
      return file;
    }
    await Future<void>.delayed(const Duration(seconds: 20));
  }
2058
  throw StateError('Did not find vmservice out file after 1 hour');
2059 2060
}

2061 2062 2063
String? _findDarwinAppInBuildDirectory(String searchDirectory) {
  for (final FileSystemEntity entity in Directory(searchDirectory)
    .listSync(recursive: true)) {
2064 2065 2066 2067 2068 2069
    if (entity.path.endsWith('.app')) {
      return entity.path;
    }
  }
  return null;
}