Dart有一种方法可以测量小代码的执行时间

Far*_*ion 15 dart

我做了一些涉及解析html的片段,想知道代码是否运行缓慢,这是可行的吗?

Ale*_*uin 30

您可以使用秒表来测量执行时间:

Stopwatch stopwatch = new Stopwatch()..start();
doSomething();
print('doSomething() executed in ${stopwatch.elapsed}');
Run Code Online (Sandbox Code Playgroud)

飞镖2:

  • 类型推断
  • 可选的 new
final stopwatch = Stopwatch()..start();
doSomething();
print('doSomething() executed in ${stopwatch.elapsed}');
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:“elapsed”返回一个“Duration”,您可以调用“inMilliseconds”、“inSeconds”等来获取首选单位。 (12认同)
  • @ArpitBhalla 这两个点是 Dart 中的 [cascade](https://dart.dev/codelabs/dart-cheatsheet#cascades) 运算符。它返回前面的表达式的值,允许您将表达式链接在一起。在这种情况下,它实际上并不需要或没有用处。一个更好的例子是添加到列表中。"正常": `列表 l = []; l.add(1); l.add(2);` 使用级联的缩写版本:`List l = []; l..add(1)..add(2);` (3认同)

Jhi*_*tos 9

在配置文件模式下使用开发工具以获得最佳结果

import 'dart:developer';

Timeline.startSync('interesting function');
// iWonderHowLongThisTakes();
Timeline.finishSync();
Run Code Online (Sandbox Code Playgroud)

https://flutter.dev/docs/testing/code-debugging#tracing-dart-code-performance


Set*_*add 7

如果你在网上,你可以得到一个高分辨率的计时器:

num time = window.performance.now();
Run Code Online (Sandbox Code Playgroud)

来自http://api.dartlang.org/docs/releases/latest/dart_html/Performance.html#now