当前位置: 首页 > news >正文

StopWatch计时器

前言

开发中,为了评估性能,我们通常会使用System.currentTimeMillis() 去计算程序运行耗时

long startTime=System.currentTimeMillis();//业务代码...
long endTime=System.currentTimeMillis();
System.out.println("耗时:"+ (endTime-startTime)+" ms");

如何使用StopWatch优雅的做程序计时器呢?

StopWatch

示例如下

@Testpublic void testStopWatch() {StopWatch stopWatch = new StopWatch();stopWatch.start("构建map装载10条记录");Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < 10; i++) {map.put(i, i + 100);}stopWatch.stop();stopWatch.start("forEach遍历map并输出");map.forEach((k,v)->{System.out.println(k+"="+v);});stopWatch.stop();stopWatch.start("iterator遍历map并输出");Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();while(iterator.hasNext()){Map.Entry<Integer, Integer> next = iterator.next();System.out.println(next.getKey()+"="+next.getValue());}stopWatch.stop();System.out.println("最后一个任务耗时:"+stopWatch.getLastTaskTimeNanos()+" ns");System.out.println("任务总耗时:"+stopWatch.getTotalTimeNanos()+" ns");System.out.println(stopWatch.prettyPrint());}

运行结果输出,可以看到StopWatch能优雅的显示程序各任务的耗时和占比。
在这里插入图片描述

StopWatch各方法解释

  • prettyPrint:格式化输出
  • getTotalTimeNanos:总消耗的时间,单位纳秒
  • getLastTaskTimeNanos:最后一个任务消耗的时间,单位纳秒
  • getLastTaskInfo: 最后一个任务的信息
  • getTaskInfo: 所有任务的信息(数组)
  • getTaskCount: 任务数
  • startTask(“任务名称”): 任务的开始,传入任务名称
  • stopTask: 停止计时器
  • setKeepTaskList: 是否维护TaskList,如果为false,则不维护TaskList
http://www.lryc.cn/news/19606.html

相关文章:

  • 常见web安全漏洞-暴力破解,xss,SQL注入,csrf
  • 11个案例讲透 Python 函数参数
  • 《分布式技术原理与算法解析》学习笔记Day21
  • 开源shell脚本系列-检查etcd集群可用性
  • 资源限制类题目七大技巧 解决所有大数据资源限制类问题
  • adb命令导出手机已安装的android应用apk文件
  • 华为CT6100双千M路由记录
  • 【AcWing-Python-785】快速排序
  • 从 JDK 8 到 JDK 18,Java 垃圾回收的十次进化
  • 虚拟机VMware Workstation Pro环境搭建
  • 【华为OD机试模拟题】用 C++ 实现 - 敏感字段加密(2023.Q1)
  • 关于Java方法重写的一些反思
  • 【C语言进阶】文件的顺序读写、随机读写、文本文件和二进制文件、文件读取结束的判定以及文件缓冲区相关知识
  • 图形编辑器:拖拽阻塞优化
  • c++ 的 Eigen库写 AX=XB的矩阵求解代码
  • 正点原子linux驱动篇
  • MATLAB绘制雷达图/蜘蛛图
  • 算法入门,十字路口选择的案例,如果是南方,则向前行
  • 父传子与子传父步骤
  • Java concurrency - Task Execution
  • 浅谈BOM
  • 每日学术速递2.24
  • SpringBoot 面试问答总结(VIP典藏版)
  • CSS 定位网页元素【快速掌握知识点】
  • 构建Docker基础镜像(ubuntu20.04+python3.7.1+chrome101+chromedriver101)
  • 最新最全Java面试知识
  • 个人电脑需求严重疲软,联想集团财务前景仍不乐观
  • 软件测试面试在简历上写了“精通”后,拥有工作经验的我被面试官问到窒息...
  • 色环电容读数方法要点总结
  • C++函数新思想和标准的输入和输出