perf_tests.dart 24.1 KB
Newer Older
1 2 3 4 5
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6
import 'dart:convert' show json;
7
import 'dart:io';
8

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

12 13
import '../framework/adb.dart';
import '../framework/framework.dart';
14
import '../framework/ios.dart';
15 16
import '../framework/utils.dart';

17
TaskFunction createComplexLayoutScrollPerfTest() {
18
  return PerfTest(
19 20 21
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
    'test_driver/scroll_perf.dart',
    'complex_layout_scroll_perf',
22
  ).run;
23 24
}

25
TaskFunction createTilesScrollPerfTest() {
26
  return PerfTest(
27 28 29 30 31 32
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
    'test_driver/scroll_perf.dart',
    'tiles_scroll_perf',
  ).run;
}

33 34 35 36 37 38 39 40
TaskFunction createHomeScrollPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/examples/flutter_gallery',
    'test_driver/scroll_perf.dart',
    'home_scroll_perf',
  ).run;
}

41 42 43 44 45 46 47 48
TaskFunction createCullOpacityPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/cull_opacity_perf.dart',
    'cull_opacity_perf',
  ).run;
}

49 50 51 52 53 54
TaskFunction createCubicBezierPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/cubic_bezier_perf.dart',
    'cubic_bezier_perf',
  ).run;
55 56 57 58 59 60 61 62
}

TaskFunction createBackdropFilterPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/backdrop_filter_perf.dart',
    'backdrop_filter_perf',
  ).run;
63 64
}

65
TaskFunction createFlutterGalleryStartupTest() {
66
  return StartupTest(
67
    '${flutterDirectory.path}/examples/flutter_gallery',
68
  ).run;
69 70
}

71
TaskFunction createComplexLayoutStartupTest() {
72
  return StartupTest(
73
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
74
  ).run;
75 76
}

77 78 79 80 81 82 83
TaskFunction createHelloWorldStartupTest() {
  return StartupTest(
    '${flutterDirectory.path}/examples/hello_world',
    reportMetrics: false,
  ).run;
}

84
TaskFunction createFlutterGalleryCompileTest() {
85
  return CompileTest('${flutterDirectory.path}/examples/flutter_gallery').run;
86 87
}

88
TaskFunction createHelloWorldCompileTest() {
89
  return CompileTest('${flutterDirectory.path}/examples/hello_world', reportPackageContentSizes: true).run;
90 91
}

92 93 94 95
TaskFunction createWebCompileTest() {
  return const WebCompileTest().run;
}

96
TaskFunction createComplexLayoutCompileTest() {
97
  return CompileTest('${flutterDirectory.path}/dev/benchmarks/complex_layout').run;
98 99
}

100
TaskFunction createFlutterViewStartupTest() {
101
  return StartupTest(
102 103
      '${flutterDirectory.path}/examples/flutter_view',
      reportMetrics: false,
104 105 106
  ).run;
}

107
TaskFunction createPlatformViewStartupTest() {
108
  return StartupTest(
109 110 111 112 113
    '${flutterDirectory.path}/examples/platform_view',
    reportMetrics: false,
  ).run;
}

114 115 116 117 118
TaskFunction createBasicMaterialCompileTest() {
  return () async {
    const String sampleAppName = 'sample_flutter_app';
    final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName');

119
    rmTree(sampleDir);
120

121
    await inDirectory<void>(Directory.systemTemp, () async {
122
      await flutter('create', options: <String>['--template=app', sampleAppName]);
123 124
    });

125
    if (!sampleDir.existsSync())
126 127
      throw 'Failed to create default Flutter app in ${sampleDir.path}';

128
    return CompileTest(sampleDir.path).run();
129
  };
130 131
}

132

133 134
/// Measure application startup performance.
class StartupTest {
135
  const StartupTest(this.testDirectory, { this.reportMetrics = true });
136 137

  final String testDirectory;
138
  final bool reportMetrics;
139

140
  Future<TaskResult> run() async {
141
    return await inDirectory<TaskResult>(testDirectory, () async {
142
      final String deviceId = (await devices.workingDevice).deviceId;
143
      await flutter('packages', options: <String>['get']);
144

145
      if (deviceOperatingSystem == DeviceOperatingSystem.ios)
146
        await prepareProvisioningCertificates(testDirectory);
147 148

      await flutter('run', options: <String>[
149
        '--verbose',
150 151 152 153
        '--profile',
        '--trace-startup',
        '-d',
        deviceId,
154
      ]);
155
      final Map<String, dynamic> data = json.decode(file('$testDirectory/build/start_up_info.json').readAsStringSync());
156

157
      if (!reportMetrics)
158
        return TaskResult.success(data);
159

160
      return TaskResult.success(data, benchmarkScoreKeys: <String>[
161
        'timeToFirstFrameMicros',
162
        'timeToFirstFrameRasterizedMicros',
163 164 165 166 167 168 169 170
      ]);
    });
  }
}

/// Measures application runtime performance, specifically per-frame
/// performance.
class PerfTest {
171
  const PerfTest(this.testDirectory, this.testTarget, this.timelineFileName);
172 173 174 175 176

  final String testDirectory;
  final String testTarget;
  final String timelineFileName;

177
  Future<TaskResult> run() {
178
    return inDirectory<TaskResult>(testDirectory, () async {
179
      final Device device = await devices.workingDevice;
180
      await device.unlock();
181
      final String deviceId = device.deviceId;
182
      await flutter('packages', options: <String>['get']);
183

184
      if (deviceOperatingSystem == DeviceOperatingSystem.ios)
185
        await prepareProvisioningCertificates(testDirectory);
186 187 188 189 190 191 192 193 194 195

      await flutter('drive', options: <String>[
        '-v',
        '--profile',
        '--trace-startup', // Enables "endless" timeline event buffering.
        '-t',
        testTarget,
        '-d',
        deviceId,
      ]);
196
      final Map<String, dynamic> data = json.decode(file('$testDirectory/build/$timelineFileName.timeline_summary.json').readAsStringSync());
197 198

      if (data['frame_count'] < 5) {
199
        return TaskResult.failure(
200 201 202 203 204
          'Timeline contains too few frames: ${data['frame_count']}. Possibly '
          'trace events are not being captured.',
        );
      }

205
      return TaskResult.success(data, benchmarkScoreKeys: <String>[
206 207 208
        'average_frame_build_time_millis',
        'worst_frame_build_time_millis',
        'missed_frame_build_budget_count',
209 210
        '90th_percentile_frame_build_time_millis',
        '99th_percentile_frame_build_time_millis',
211 212
        'average_frame_rasterizer_time_millis',
        'worst_frame_rasterizer_time_millis',
213
        'missed_frame_rasterizer_budget_count',
214 215
        '90th_percentile_frame_rasterizer_time_millis',
        '99th_percentile_frame_rasterizer_time_millis',
216 217 218 219 220
      ]);
    });
  }
}

221 222 223 224 225 226 227 228 229 230 231 232 233 234
/// 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>{};
    await inDirectory<TaskResult>('${flutterDirectory.path}/examples/hello_world', () async {
      await flutter('packages', options: <String>['get']);
      await evalFlutter('build', options: <String>[
        'web',
        '-v',
        '--release',
        '--no-pub',
235 236 237
      ], environment: <String, String>{
        'FLUTTER_WEB': 'true',
      });
238 239 240 241 242 243 244 245 246 247 248
      final String output = '${flutterDirectory.path}/examples/hello_world/build/web/main.dart.js';
      await _measureSize('hello_world', output, metrics);
      return null;
    });
    await inDirectory<TaskResult>('${flutterDirectory.path}/examples/flutter_gallery', () async {
      await flutter('packages', options: <String>['get']);
      await evalFlutter('build', options: <String>[
        'web',
        '-v',
        '--release',
        '--no-pub',
249 250 251
      ], environment: <String, String>{
        'FLUTTER_WEB': 'true',
      });
252 253 254 255 256 257 258 259 260 261
      final String output = '${flutterDirectory.path}/examples/flutter_gallery/build/web/main.dart.js';
      await _measureSize('flutter_gallery', output, metrics);
      return null;
    });
    const String sampleAppName = 'sample_flutter_app';
    final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName');

    rmTree(sampleDir);

    await inDirectory<void>(Directory.systemTemp, () async {
262 263 264
      await flutter('create', options: <String>['--template=app', '--web', sampleAppName], environment: <String, String>{
          'FLUTTER_WEB': 'true',
        });
265 266 267 268 269 270 271
      await inDirectory(sampleDir, () async {
        await flutter('packages', options: <String>['get']);
        await evalFlutter('build', options: <String>[
          'web',
          '-v',
          '--release',
          '--no-pub',
272 273 274
        ], environment: <String, String>{
          'FLUTTER_WEB': 'true',
        });
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        await _measureSize('basic_material_app', path.join(sampleDir.path, 'build/web/main.dart.js'), metrics);
      });
    });
    return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
  }

  static Future<void> _measureSize(String metric, String output, Map<String, Object> metrics) async {
    final ProcessResult result = await Process.run('du', <String>['-k', output]);
    await Process.run('gzip',<String>['-k', '9', output]);
    final ProcessResult resultGzip = await Process.run('du', <String>['-k', output + '.gz']);
    metrics['${metric}_dart2js_size'] = _parseDu(result.stdout);
    metrics['${metric}_dart2js_size_gzip'] = _parseDu(resultGzip.stdout);
  }

  static int _parseDu(String source) {
    return int.parse(source.split(RegExp(r'\s+')).first.trim());
  }
}

294
/// Measures how long it takes to compile a Flutter app and how big the compiled
295
/// code is.
296
class CompileTest {
297
  const CompileTest(this.testDirectory, { this.reportPackageContentSizes = false });
298 299

  final String testDirectory;
300
  final bool reportPackageContentSizes;
301

302
  Future<TaskResult> run() async {
303
    return await inDirectory<TaskResult>(testDirectory, () async {
304
      final Device device = await devices.workingDevice;
305
      await device.unlock();
306
      await flutter('packages', options: <String>['get']);
307

308 309 310 311 312
      final Map<String, dynamic> metrics = <String, dynamic>{
        ...await _compileAot(),
        ...await _compileApp(reportPackageContentSizes: reportPackageContentSizes),
        ...await _compileDebug(),
      };
313

314
      return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
315 316
    });
  }
317

318
  static Future<Map<String, dynamic>> _compileAot() async {
Ian Hickson's avatar
Ian Hickson committed
319
    // Generate blobs instead of assembly.
320
    await flutter('clean');
321
    final Stopwatch watch = Stopwatch()..start();
322
    final List<String> options = <String>[
323 324
      'aot',
      '-v',
325
      '--extra-gen-snapshot-options=--print_snapshot_sizes',
326 327
      '--release',
      '--no-pub',
Ian Hickson's avatar
Ian Hickson committed
328
      '--target-platform',
329
    ];
Ian Hickson's avatar
Ian Hickson committed
330 331 332 333 334 335 336 337
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.add('ios');
        break;
      case DeviceOperatingSystem.android:
        options.add('android-arm');
        break;
    }
338
    final String compileLog = await evalFlutter('build', options: options);
339 340
    watch.stop();

341
    final RegExp metricExpression = RegExp(r'([a-zA-Z]+)\(CodeSize\)\: (\d+)');
342 343 344 345
    final Map<String, dynamic> metrics = <String, dynamic>{};
    for (Match m in metricExpression.allMatches(compileLog)) {
      metrics[_sdkNameToMetricName(m.group(1))] = int.parse(m.group(2));
    }
346 347 348
    if (metrics.length != _kSdkNameToMetricNameMapping.length) {
      throw 'Expected metrics: ${_kSdkNameToMetricNameMapping.keys}, but got: ${metrics.keys}.';
    }
349
    metrics['aot_snapshot_compile_millis'] = watch.elapsedMilliseconds;
350 351 352 353

    return metrics;
  }

354
  static Future<Map<String, dynamic>> _compileApp({ bool reportPackageContentSizes = false }) async {
355
    await flutter('clean');
356
    final Stopwatch watch = Stopwatch();
357 358
    int releaseSizeInBytes;
    final List<String> options = <String>['--release'];
359 360
    final Map<String, dynamic> metrics = <String, dynamic>{};

Ian Hickson's avatar
Ian Hickson committed
361 362 363 364 365 366 367
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.insert(0, 'ios');
        await prepareProvisioningCertificates(cwd);
        watch.start();
        await flutter('build', options: options);
        watch.stop();
368
        final String appPath =  '$cwd/build/ios/Release-iphoneos/Runner.app/';
369
        // IPAs are created manually, https://flutter.dev/ios-release/
370
        await exec('tar', <String>['-zcf', 'build/app.ipa', appPath]);
Ian Hickson's avatar
Ian Hickson committed
371
        releaseSizeInBytes = await file('$cwd/build/app.ipa').length();
372 373
        if (reportPackageContentSizes)
          metrics.addAll(await getSizesFromIosApp(appPath));
Ian Hickson's avatar
Ian Hickson committed
374 375 376
        break;
      case DeviceOperatingSystem.android:
        options.insert(0, 'apk');
377
        options.add('--target-platform=android-arm');
Ian Hickson's avatar
Ian Hickson committed
378 379 380
        watch.start();
        await flutter('build', options: options);
        watch.stop();
381 382
        String apkPath = '$cwd/build/app/outputs/apk/app.apk';
        File apk = file(apkPath);
383 384
        if (!apk.existsSync()) {
          // Pre Android SDK 26 path
385 386
          apkPath = '$cwd/build/app/outputs/apk/app-release.apk';
          apk = file(apkPath);
387 388
        }
        releaseSizeInBytes = apk.lengthSync();
389 390
        if (reportPackageContentSizes)
          metrics.addAll(await getSizesFromApk(apkPath));
Ian Hickson's avatar
Ian Hickson committed
391
        break;
392
    }
393

394
    metrics.addAll(<String, dynamic>{
395 396
      'release_full_compile_millis': watch.elapsedMilliseconds,
      'release_size_bytes': releaseSizeInBytes,
397 398 399
    });

    return metrics;
400 401
  }

402
  static Future<Map<String, dynamic>> _compileDebug() async {
403
    await flutter('clean');
404
    final Stopwatch watch = Stopwatch();
Ian Hickson's avatar
Ian Hickson committed
405 406 407 408 409 410 411 412
    final List<String> options = <String>['--debug'];
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.insert(0, 'ios');
        await prepareProvisioningCertificates(cwd);
        break;
      case DeviceOperatingSystem.android:
        options.insert(0, 'apk');
413
        options.add('--target-platform=android-arm');
Ian Hickson's avatar
Ian Hickson committed
414
        break;
415
    }
Ian Hickson's avatar
Ian Hickson committed
416 417 418
    watch.start();
    await flutter('build', options: options);
    watch.stop();
419 420

    return <String, dynamic>{
421
      'debug_full_compile_millis': watch.elapsedMilliseconds,
422 423 424
    };
  }

425
  static const Map<String, String> _kSdkNameToMetricNameMapping = <String, String> {
426 427 428 429 430 431 432
    'VMIsolate': 'aot_snapshot_size_vmisolate',
    'Isolate': 'aot_snapshot_size_isolate',
    'ReadOnlyData': 'aot_snapshot_size_rodata',
    'Instructions': 'aot_snapshot_size_instructions',
    'Total': 'aot_snapshot_size_total',
  };

433 434
  static String _sdkNameToMetricName(String sdkName) {

435
    if (!_kSdkNameToMetricNameMapping.containsKey(sdkName))
436 437
      throw 'Unrecognized SDK snapshot metric name: $sdkName';

438
    return _kSdkNameToMetricNameMapping[sdkName];
439
  }
440

441 442
  static Future<Map<String, dynamic>> getSizesFromIosApp(String appPath) async {
    // Thin the binary to only contain one architecture.
443
    final String xcodeBackend = path.join(flutterDirectory.path, 'packages', 'flutter_tools', 'bin', 'xcode_backend.sh');
444 445
    await exec(xcodeBackend, <String>['thin'], environment: <String, String>{
      'ARCHS': 'arm64',
446 447
      'WRAPPER_NAME': path.basename(appPath),
      'TARGET_BUILD_DIR': path.dirname(appPath),
448 449
    });

450 451
    final File appFramework = File(path.join(appPath, 'Frameworks', 'App.framework', 'App'));
    final File flutterFramework = File(path.join(appPath, 'Frameworks', 'Flutter.framework', 'Flutter'));
452 453 454 455 456 457 458 459

    return <String, dynamic>{
      'app_framework_uncompressed_bytes': await appFramework.length(),
      'flutter_framework_uncompressed_bytes': await flutterFramework.length(),
    };
  }


460 461 462 463 464 465 466
  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++) {
467
      final _UnzipListEntry entry = _UnzipListEntry.fromLine(lines[i]);
468 469 470 471
      fileToMetadata[entry.path] = entry;
    }

    final _UnzipListEntry libflutter = fileToMetadata['lib/armeabi-v7a/libflutter.so'];
472
    final _UnzipListEntry libapp = fileToMetadata['lib/armeabi-v7a/libapp.so'];
473
    final _UnzipListEntry license = fileToMetadata['assets/flutter_assets/LICENSE'];
474 475 476 477

    return <String, dynamic>{
      'libflutter_uncompressed_bytes': libflutter.uncompressedSize,
      'libflutter_compressed_bytes': libflutter.compressedSize,
478 479
      'libapp_uncompressed_bytes': libapp.uncompressedSize,
      'libapp_compressed_bytes': libapp.compressedSize,
480 481
      'license_uncompressed_bytes': license.uncompressedSize,
      'license_compressed_bytes': license.compressedSize,
482 483
    };
  }
484
}
485

486
/// Measure application memory usage.
487
class MemoryTest {
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
  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`.
  Future<void> get receivedNextMessage => _receivedNextMessage?.future;
  Completer<void> _receivedNextMessage;
  String _nextMessage;

  /// 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;
504
    _receivedNextMessage = Completer<void>();
505
  }
506

507
  int get iterationCount => 10;
508

509 510
  Device get device => _device;
  Device _device;
511

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

      _device = await devices.workingDevice;
518 519 520
      await device.unlock();
      await flutter('packages', options: <String>['get']);

521
      if (deviceOperatingSystem == DeviceOperatingSystem.ios)
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
        await prepareProvisioningCertificates(project);

      final StreamSubscription<String> adb = device.logcat.listen(
        (String data) {
          if (data.contains('==== MEMORY BENCHMARK ==== $_nextMessage ===='))
            _receivedNextMessage.complete();
        },
      );

      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...');
        await device.stop(package);
541
        await Future<void>.delayed(const Duration(milliseconds: 10));
542
      }
543

544 545
      await adb.cancel();

546 547 548
      final ListStatistics startMemoryStatistics = ListStatistics(_startMemory);
      final ListStatistics endMemoryStatistics = ListStatistics(_endMemory);
      final ListStatistics diffMemoryStatistics = ListStatistics(_diffMemory);
549

550 551 552 553 554
      final Map<String, dynamic> memoryUsage = <String, dynamic>{
        ...startMemoryStatistics.asMap('start'),
        ...endMemoryStatistics.asMap('end'),
        ...diffMemoryStatistics.asMap('diff'),
      };
555

556 557 558 559 560
      _device = null;
      _startMemory.clear();
      _endMemory.clear();
      _diffMemory.clear();

561
      return TaskResult.success(memoryUsage, benchmarkScoreKeys: memoryUsage.keys.toList());
562 563
    });
  }
564

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
  /// 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',
      '-d', device.deviceId,
      test,
    ]);
    print('awaiting "ready" message...');
    await receivedNextMessage;
  }
581

582
  /// To change the behavior of the test, override this.
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
  ///
  /// 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...');
    await device.tap(100, 100);
    print('awaiting "done" message...');
    await receivedNextMessage;

    await recordEnd();
  }
600

601 602 603
  final List<int> _startMemory = <int>[];
  final List<int> _endMemory = <int>[];
  final List<int> _diffMemory = <int>[];
604

605
  Map<String, dynamic> _startMemoryUsage;
606

607 608 609 610 611 612
  @protected
  Future<void> recordStart() async {
    assert(_startMemoryUsage == null);
    print('snapshotting memory usage...');
    _startMemoryUsage = await device.getMemoryStats(package);
  }
613

614 615 616 617 618 619 620 621 622 623
  @protected
  Future<void> recordEnd() async {
    assert(_startMemoryUsage != null);
    print('snapshotting memory usage...');
    final Map<String, dynamic> endMemoryUsage = await device.getMemoryStats(package);
    _startMemory.add(_startMemoryUsage['total_kb']);
    _endMemory.add(endMemoryUsage['total_kb']);
    _diffMemory.add(endMemoryUsage['total_kb'] - _startMemoryUsage['total_kb']);
  }
}
624

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
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';
  }
  throw ArgumentError('Unexpected value for enum $flavor');
}

641
class ReportedDurationTest {
642
  ReportedDurationTest(this.flavor, this.project, this.test, this.package, this.durationPattern);
643

644
  final ReportedDurationTestFlavor flavor;
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
  final String project;
  final String test;
  final String package;
  final RegExp durationPattern;

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

  int get iterationCount => 10;

  Device get device => _device;
  Device _device;

  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;
      await device.unlock();
      await flutter('packages', options: <String>['get']);

      if (deviceOperatingSystem == DeviceOperatingSystem.ios)
        await prepareProvisioningCertificates(project);

      final StreamSubscription<String> adb = device.logcat.listen(
        (String data) {
          if (durationPattern.hasMatch(data))
            durationCompleter.complete(int.parse(durationPattern.firstMatch(data).group(1)));
        },
      );
      print('launching $project$test on device...');
      await flutter('run', options: <String>[
        '--verbose',
678
        '--${_reportedDurationTestToString(flavor)}',
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
        '--no-resident',
        '-d', device.deviceId,
        test,
      ]);

      final int duration = await durationCompleter.future;
      print('terminating...');
      await device.stop(package);
      await adb.cancel();

      _device = null;

      final Map<String, dynamic> reportedDuration = <String, dynamic>{
        'duration': duration
      };
      _device = null;

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

701 702 703 704 705 706
/// Holds simple statistics of an odd-lengthed list of integers.
class ListStatistics {
  factory ListStatistics(Iterable<int> data) {
    assert(data.isNotEmpty);
    assert(data.length % 2 == 1);
    final List<int> sortedData = data.toList()..sort();
707
    return ListStatistics._(
708 709 710 711 712
      sortedData.first,
      sortedData.last,
      sortedData[(sortedData.length - 1) ~/ 2],
    );
  }
713

714
  const ListStatistics._(this.min, this.max, this.median);
715

716 717 718 719 720 721 722 723 724 725
  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,
    };
726 727
  }
}
728 729 730

class _UnzipListEntry {
  factory _UnzipListEntry.fromLine(String line) {
731
    final List<String> data = line.trim().split(RegExp('\\s+'));
732
    assert(data.length == 8);
733
    return _UnzipListEntry._(
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
      uncompressedSize:  int.parse(data[0]),
      compressedSize: int.parse(data[2]),
      path: data[7],
    );
  }

  _UnzipListEntry._({
    @required this.uncompressedSize,
    @required this.compressedSize,
    @required this.path,
  }) : assert(uncompressedSize != null),
       assert(compressedSize != null),
       assert(compressedSize <= uncompressedSize),
       assert(path != null);

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