用StopWatch优雅替代currentTimeMillis计算程序执行耗时

别再用System.currentTimeMillis()计算程序执行耗时了,拥抱StopWatch优雅来优雅的计算,代码更简洁效率更高,本文带你了解StopWatch的使用

需求

有时需要记录程序执行时间,最简单就是打印当前时间与执行完时间的差值,缺点是:

执行大量测试的话就很麻烦

不直观

如果想对执行的时间做进一步控制,则需要在程序中很多地方修改

于是 Spring提供了一个StopWatch类可以做类似任务执行时间控制,即封装了一个对开始时间,结束时间记录工具

案例

统计输出总耗时

import org.springframework.util.StopWatch; public class SpringStopWatchExample { public static void main (String[] args) throws InterruptedException { StopWatch sw = new StopWatch(); sw.start(); //long task simulation Thread.sleep(1000); sw.stop(); System.out.println(sw.getTotalTimeMillis()); } }

输出最后一个任务的耗时

public class SpringStopWatchExample2 { public static void main (String[] args) throws InterruptedException { StopWatch sw = new StopWatch(); sw.start("A");//setting a task name //long task simulation Thread.sleep(1000); sw.stop(); System.out.println(sw.getLastTasktimeMillis()); } }

以优雅的格式打出所有任务的耗时以及占比

import org.springframework.util.StopWatch; public class SpringStopWatchExample3 { public static void main (String[] args) throws InterruptedException { StopWatch sw = new StopWatch(); sw.start("A"); Thread.sleep(500); sw.stop(); sw.start("B"); Thread.sleep(300); sw.stop(); sw.start("C"); Thread.sleep(200); sw.stop(); System.out.println(sw.prettyPrint()); } }

序列服务输出耗时信息

@Override public long nextSeq(String name) { StopWatch watch = new StopWatch(); watch.start("单序列获取总消耗"); long sequence = generator.generateId(name); watch.stop(); logger.info(watch.prettyPrint()); return sequence; }

getTotalTimeSeconds() 获取总耗时秒,同时也有获取毫秒的方法

prettyPrint() 优雅的格式打印结果,表格形式

shortSummary() 返回简短的总耗时描述

getTaskCount() 返回统计时间任务的数量

getLastTaskInfo().getTaskName() 返回最后一个任务TaskInfo对象的名称

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...