You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dart中测量代码块的毫秒级执行时长

用Dart原生功能测量代码执行时长(毫秒级)

Dart原生自带的Stopwatch类是最适合的工具,它属于dart:core库,无需额外依赖,直接就能实现毫秒级计时。

具体实现步骤:

  • 初始化Stopwatch实例并调用start()启动计时
  • 运行需要测试的代码块
  • 调用stop()终止计时,通过elapsedMilliseconds属性获取毫秒级耗时

修正原代码变量错误后的完整示例:

void main() {
  final stopwatch = Stopwatch()..start();

  for(int index = 0; index < 1000000; index += 1) {
    print(index); // 原代码中print(i)是错误的,这里修正为print(index)
  }

  stopwatch.stop();
  print('代码执行总耗时:${stopwatch.elapsedMilliseconds} 毫秒');
}

补充说明:如果不需要暂停计时,也可以不调用stop(),直接在代码执行完后获取elapsedMilliseconds,结果是一致的。

内容的提问来源于stack exchange,提问作者Gwhyyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:45:34