perf_tests.dart 19.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 19 20 21
  return new PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
    'test_driver/scroll_perf.dart',
    'complex_layout_scroll_perf',
22
  ).run;
23 24
}

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

33
TaskFunction createFlutterGalleryStartupTest() {
34 35
  return new StartupTest(
    '${flutterDirectory.path}/examples/flutter_gallery',
36
  ).run;
37 38
}

39
TaskFunction createComplexLayoutStartupTest() {
40 41
  return new StartupTest(
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
42
  ).run;
43 44
}

45 46
TaskFunction createFlutterGalleryCompileTest() {
  return new CompileTest('${flutterDirectory.path}/examples/flutter_gallery').run;
47 48
}

49
TaskFunction createHelloWorldCompileTest() {
50
  return new CompileTest('${flutterDirectory.path}/examples/hello_world', reportPackageContentSizes: true).run;
51 52
}

53 54
TaskFunction createComplexLayoutCompileTest() {
  return new CompileTest('${flutterDirectory.path}/dev/benchmarks/complex_layout').run;
55 56
}

57 58 59 60
TaskFunction createFlutterViewStartupTest() {
  return new StartupTest(
      '${flutterDirectory.path}/examples/flutter_view',
      reportMetrics: false,
61 62 63
  ).run;
}

64 65 66 67 68 69 70
TaskFunction createPlatformViewStartupTest() {
  return new StartupTest(
    '${flutterDirectory.path}/examples/platform_view',
    reportMetrics: false,
  ).run;
}

71 72 73 74 75 76 77 78
TaskFunction createBasicMaterialCompileTest() {
  return () async {
    const String sampleAppName = 'sample_flutter_app';
    final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName');

    if (await sampleDir.exists())
      rmTree(sampleDir);

79 80 81 82 83 84 85
    await inDirectory(Directory.systemTemp, () async {
      await flutter('create', options: <String>[sampleAppName]);
    });

    if (!(await sampleDir.exists()))
      throw 'Failed to create default Flutter app in ${sampleDir.path}';

86 87
    return new CompileTest(sampleDir.path).run();
  };
88 89
}

90

91 92
/// Measure application startup performance.
class StartupTest {
93
  static const Duration _startupTimeout = Duration(minutes: 5);
94

95
  const StartupTest(this.testDirectory, { this.reportMetrics = true });
96 97

  final String testDirectory;
98
  final bool reportMetrics;
99

100
  Future<TaskResult> run() async {
101
    return await inDirectory(testDirectory, () async {
102
      final String deviceId = (await devices.workingDevice).deviceId;
103
      await flutter('packages', options: <String>['get']);
104

105
      if (deviceOperatingSystem == DeviceOperatingSystem.ios)
106
        await prepareProvisioningCertificates(testDirectory);
107 108

      await flutter('run', options: <String>[
109
        '--verbose',
110 111 112 113 114
        '--profile',
        '--trace-startup',
        '-d',
        deviceId,
      ]).timeout(_startupTimeout);
115
      final Map<String, dynamic> data = json.decode(file('$testDirectory/build/start_up_info.json').readAsStringSync());
116

117 118
      if (!reportMetrics)
        return new TaskResult.success(data);
119

120 121 122 123 124 125 126 127 128 129
      return new TaskResult.success(data, benchmarkScoreKeys: <String>[
        'timeToFirstFrameMicros',
      ]);
    });
  }
}

/// Measures application runtime performance, specifically per-frame
/// performance.
class PerfTest {
130
  const PerfTest(this.testDirectory, this.testTarget, this.timelineFileName);
131 132 133 134 135

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

136
  Future<TaskResult> run() {
137
    return inDirectory(testDirectory, () async {
138
      final Device device = await devices.workingDevice;
139
      await device.unlock();
140
      final String deviceId = device.deviceId;
141
      await flutter('packages', options: <String>['get']);
142

143
      if (deviceOperatingSystem == DeviceOperatingSystem.ios)
144
        await prepareProvisioningCertificates(testDirectory);
145 146 147 148 149 150 151 152 153 154

      await flutter('drive', options: <String>[
        '-v',
        '--profile',
        '--trace-startup', // Enables "endless" timeline event buffering.
        '-t',
        testTarget,
        '-d',
        deviceId,
      ]);
155
      final Map<String, dynamic> data = json.decode(file('$testDirectory/build/$timelineFileName.timeline_summary.json').readAsStringSync());
156 157 158 159 160 161 162 163

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

164 165 166 167
      return new TaskResult.success(data, benchmarkScoreKeys: <String>[
        'average_frame_build_time_millis',
        'worst_frame_build_time_millis',
        'missed_frame_build_budget_count',
168 169
        'average_frame_rasterizer_time_millis',
        'worst_frame_rasterizer_time_millis',
170 171
        '90th_percentile_frame_rasterizer_time_millis',
        '99th_percentile_frame_rasterizer_time_millis',
172 173 174 175 176
      ]);
    });
  }
}

177
/// Measures how long it takes to compile a Flutter app and how big the compiled
178
/// code is.
179
class CompileTest {
180
  const CompileTest(this.testDirectory, { this.reportPackageContentSizes = false });
181 182

  final String testDirectory;
183
  final bool reportPackageContentSizes;
184

185
  Future<TaskResult> run() async {
186
    return await inDirectory(testDirectory, () async {
187
      final Device device = await devices.workingDevice;
188
      await device.unlock();
189
      await flutter('packages', options: <String>['get']);
190

191
      final Map<String, dynamic> metrics = <String, dynamic>{}
192
        ..addAll(await _compileAot())
193
        ..addAll(await _compileApp(reportPackageContentSizes: reportPackageContentSizes))
194
        ..addAll(await _compileDebug());
195

196
      return new TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
197 198
    });
  }
199

200
  static Future<Map<String, dynamic>> _compileAot({ bool previewDart2 = true }) async {
Ian Hickson's avatar
Ian Hickson committed
201
    // Generate blobs instead of assembly.
202
    await flutter('clean');
203
    final Stopwatch watch = new Stopwatch()..start();
204
    final List<String> options = <String>[
205 206
      'aot',
      '-v',
207
      '--extra-gen-snapshot-options=--print_snapshot_sizes',
208 209
      '--release',
      '--no-pub',
Ian Hickson's avatar
Ian Hickson committed
210
      '--target-platform',
211
    ];
Ian Hickson's avatar
Ian Hickson committed
212 213 214 215 216 217 218 219
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.add('ios');
        break;
      case DeviceOperatingSystem.android:
        options.add('android-arm');
        break;
    }
220 221 222 223
    if (previewDart2)
      options.add('--preview-dart-2');
    else
      options.add('--no-preview-dart-2');
224
    setLocalEngineOptionIfNecessary(options);
225
    final String compileLog = await evalFlutter('build', options: options);
226 227 228
    watch.stop();

    final RegExp metricExpression = new RegExp(r'([a-zA-Z]+)\(CodeSize\)\: (\d+)');
229 230 231 232
    final Map<String, dynamic> metrics = <String, dynamic>{};
    for (Match m in metricExpression.allMatches(compileLog)) {
      metrics[_sdkNameToMetricName(m.group(1))] = int.parse(m.group(2));
    }
233 234 235
    if (metrics.length != _kSdkNameToMetricNameMapping.length) {
      throw 'Expected metrics: ${_kSdkNameToMetricNameMapping.keys}, but got: ${metrics.keys}.';
    }
236
    metrics['aot_snapshot_compile_millis'] = watch.elapsedMilliseconds;
237 238 239 240

    return metrics;
  }

241
  static Future<Map<String, dynamic>> _compileApp({ bool previewDart2 = true, bool reportPackageContentSizes = false }) async {
242
    await flutter('clean');
243 244 245
    final Stopwatch watch = new Stopwatch();
    int releaseSizeInBytes;
    final List<String> options = <String>['--release'];
246 247 248 249
    if (previewDart2)
      options.add('--preview-dart-2');
    else
      options.add('--no-preview-dart-2');
250
    setLocalEngineOptionIfNecessary(options);
251 252
    final Map<String, dynamic> metrics = <String, dynamic>{};

Ian Hickson's avatar
Ian Hickson committed
253 254 255 256 257 258 259
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.insert(0, 'ios');
        await prepareProvisioningCertificates(cwd);
        watch.start();
        await flutter('build', options: options);
        watch.stop();
260 261 262
        final String appPath =  '$cwd/build/ios/Release-iphoneos/Runner.app/';
        // IPAs are created manually, https://flutter.io/ios-release/
        await exec('tar', <String>['-zcf', 'build/app.ipa', appPath]);
Ian Hickson's avatar
Ian Hickson committed
263
        releaseSizeInBytes = await file('$cwd/build/app.ipa').length();
264 265
        if (reportPackageContentSizes)
          metrics.addAll(await getSizesFromIosApp(appPath));
Ian Hickson's avatar
Ian Hickson committed
266 267 268 269 270 271
        break;
      case DeviceOperatingSystem.android:
        options.insert(0, 'apk');
        watch.start();
        await flutter('build', options: options);
        watch.stop();
272 273
        String apkPath = '$cwd/build/app/outputs/apk/app.apk';
        File apk = file(apkPath);
274 275
        if (!apk.existsSync()) {
          // Pre Android SDK 26 path
276 277
          apkPath = '$cwd/build/app/outputs/apk/app-release.apk';
          apk = file(apkPath);
278 279
        }
        releaseSizeInBytes = apk.lengthSync();
280 281
        if (reportPackageContentSizes)
          metrics.addAll(await getSizesFromApk(apkPath));
Ian Hickson's avatar
Ian Hickson committed
282
        break;
283
    }
284

285
    metrics.addAll(<String, dynamic>{
286 287
      'release_full_compile_millis': watch.elapsedMilliseconds,
      'release_size_bytes': releaseSizeInBytes,
288 289 290
    });

    return metrics;
291 292
  }

293
  static Future<Map<String, dynamic>> _compileDebug({ bool previewDart2 = true }) async {
294
    await flutter('clean');
295
    final Stopwatch watch = new Stopwatch();
Ian Hickson's avatar
Ian Hickson committed
296
    final List<String> options = <String>['--debug'];
297 298 299 300
    if (previewDart2)
      options.add('--preview-dart-2');
    else
      options.add('--no-preview-dart-2');
301
    setLocalEngineOptionIfNecessary(options);
Ian Hickson's avatar
Ian Hickson committed
302 303 304 305 306 307 308 309
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.insert(0, 'ios');
        await prepareProvisioningCertificates(cwd);
        break;
      case DeviceOperatingSystem.android:
        options.insert(0, 'apk');
        break;
310
    }
Ian Hickson's avatar
Ian Hickson committed
311 312 313
    watch.start();
    await flutter('build', options: options);
    watch.stop();
314 315

    return <String, dynamic>{
316
      'debug_full_compile_millis': watch.elapsedMilliseconds,
317 318 319
    };
  }

320
  static const Map<String, String> _kSdkNameToMetricNameMapping = <String, String> {
321 322 323 324 325 326 327
    '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',
  };

328 329
  static String _sdkNameToMetricName(String sdkName) {

330
    if (!_kSdkNameToMetricNameMapping.containsKey(sdkName))
331 332
      throw 'Unrecognized SDK snapshot metric name: $sdkName';

333
    return _kSdkNameToMetricNameMapping[sdkName];
334
  }
335

336 337
  static Future<Map<String, dynamic>> getSizesFromIosApp(String appPath) async {
    // Thin the binary to only contain one architecture.
338
    final String xcodeBackend = path.join(flutterDirectory.path, 'packages', 'flutter_tools', 'bin', 'xcode_backend.sh');
339 340
    await exec(xcodeBackend, <String>['thin'], environment: <String, String>{
      'ARCHS': 'arm64',
341 342
      'WRAPPER_NAME': path.basename(appPath),
      'TARGET_BUILD_DIR': path.dirname(appPath),
343 344
    });

345 346
    final File appFramework = new File(path.join(appPath, 'Frameworks', 'App.framework', 'App'));
    final File flutterFramework = new File(path.join(appPath, 'Frameworks', 'Flutter.framework', 'Flutter'));
347 348 349 350 351 352 353 354

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


355 356 357 358 359 360 361 362 363 364 365
  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++) {
      final _UnzipListEntry entry = new _UnzipListEntry.fromLine(lines[i]);
      fileToMetadata[entry.path] = entry;
    }

366
    final _UnzipListEntry icudtl = fileToMetadata['assets/flutter_shared/icudtl.dat'];
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    final _UnzipListEntry libflutter = fileToMetadata['lib/armeabi-v7a/libflutter.so'];
    final _UnzipListEntry isolateSnapshotData = fileToMetadata['assets/isolate_snapshot_data'];
    final _UnzipListEntry isolateSnapshotInstr = fileToMetadata['assets/isolate_snapshot_instr'];
    final _UnzipListEntry vmSnapshotData = fileToMetadata['assets/vm_snapshot_data'];
    final _UnzipListEntry vmSnapshotInstr = fileToMetadata['assets/vm_snapshot_instr'];

    return <String, dynamic>{
      'icudtl_uncompressed_bytes': icudtl.uncompressedSize,
      'icudtl_compressed_bytes': icudtl.compressedSize,
      'libflutter_uncompressed_bytes': libflutter.uncompressedSize,
      'libflutter_compressed_bytes': libflutter.compressedSize,
      'snapshot_uncompressed_bytes': isolateSnapshotData.uncompressedSize +
          isolateSnapshotInstr.uncompressedSize +
          vmSnapshotData.uncompressedSize +
          vmSnapshotInstr.uncompressedSize,
      'snapshot_compressed_bytes': isolateSnapshotData.compressedSize +
          isolateSnapshotInstr.compressedSize +
          vmSnapshotData.compressedSize +
          vmSnapshotInstr.compressedSize,
    };
  }
388
}
389

390
/// Measure application memory usage.
391
class MemoryTest {
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
  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;
    _receivedNextMessage = new Completer<void>();
  }
410

411
  int get iterationCount => 15;
412

413 414
  Device get device => _device;
  Device _device;
415

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

      _device = await devices.workingDevice;
422 423 424
      await device.unlock();
      await flutter('packages', options: <String>['get']);

425
      if (deviceOperatingSystem == DeviceOperatingSystem.ios)
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
        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);
        await new Future<void>.delayed(const Duration(milliseconds: 10));
446
      }
447

448 449 450 451 452 453 454 455 456 457
      await adb.cancel();

      final ListStatistics startMemoryStatistics = new ListStatistics(_startMemory);
      final ListStatistics endMemoryStatistics = new ListStatistics(_endMemory);
      final ListStatistics diffMemoryStatistics = new ListStatistics(_diffMemory);

      final Map<String, dynamic> memoryUsage = <String, dynamic>{};
      memoryUsage.addAll(startMemoryStatistics.asMap('start'));
      memoryUsage.addAll(endMemoryStatistics.asMap('end'));
      memoryUsage.addAll(diffMemoryStatistics.asMap('diff'));
458

459 460 461 462 463 464
      _device = null;
      _startMemory.clear();
      _endMemory.clear();
      _diffMemory.clear();

      return new TaskResult.success(memoryUsage, benchmarkScoreKeys: memoryUsage.keys.toList());
465 466
    });
  }
467

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
  /// 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;
  }
484

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
  /// To change the behaviour of the test, override this.
  ///
  /// 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();
  }
503

504 505 506
  final List<int> _startMemory = <int>[];
  final List<int> _endMemory = <int>[];
  final List<int> _diffMemory = <int>[];
507

508
  Map<String, dynamic> _startMemoryUsage;
509

510 511 512 513 514 515
  @protected
  Future<void> recordStart() async {
    assert(_startMemoryUsage == null);
    print('snapshotting memory usage...');
    _startMemoryUsage = await device.getMemoryStats(package);
  }
516

517 518 519 520 521 522 523 524 525 526
  @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']);
  }
}
527

528 529 530 531 532 533 534 535 536 537 538 539
/// 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();
    return new ListStatistics._(
      sortedData.first,
      sortedData.last,
      sortedData[(sortedData.length - 1) ~/ 2],
    );
  }
540

541
  const ListStatistics._(this.min, this.max, this.median);
542

543 544 545 546 547 548 549 550 551 552
  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,
    };
553 554
  }
}
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

class _UnzipListEntry {
  factory _UnzipListEntry.fromLine(String line) {
    final List<String> data = line.trim().split(new RegExp('\\s+'));
    assert(data.length == 8);
    return new _UnzipListEntry._(
      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;
}