如何在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
相关产品推荐
相关产品推荐

