Java计时新姿势StopWatch、Instant

287 阅读1分钟

Java计时新姿势StopWatch、Instant

一、原始方法

很多时候我们在做接口都会测试任务执行时间,或者代码片端的执行时间。特别是在需要高性能的情况下,调优哪里的导致的缓慢问题,就会希望看到各执行的耗时时间,通常情况下我们会直接计算时间的差值来完成。

Thread.sleep(2000);
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start) + "ms");

事实上该方法通过获取执行完成时间与执行开始时间的差值得到程序的执行时间,简单直接有效,但想必写多了也是比较烦人的,尤其是碰到不可描述的代码时,会更加的让人忍不住多写几个bug聊表敬意,而且如果想对执行的时间做进一步控制,则需要在程序中很多地方修改。此时会想是否有一个工具类,提供了这些方法,刚好可以满足这种场景?我们可以利用已有的工具类中的秒表,常见的秒表工具类有 org.springframework.util.StopWatchorg.apache.commons.lang.time.StopWatch以及谷歌提供的guava中的秒表(这个我没怎么用过)。这里重点讲下基于spring、Apache的使用

二、Spring下的StopWatch使用

StopWatch stopWatch = new StopWatch();
stopWatch.start("任务1");
Thread.sleep(3000);
//System.out.println("当前任务名称:" + stopWatch.currentTaskName());
stopWatch.stop();

stopWatch.start("任务2");
Thread.sleep(2000);
//System.out.println("当前任务名称:" + stopWatch.currentTaskName());
stopWatch.stop();

// 打印出耗时
System.out.println(stopWatch.prettyPrint());
System.out.println(stopWatch.shortSummary());
// stop后它的值为null
System.out.println(stopWatch.currentTaskName());

// 最后一个任务的相关信息
System.out.println(stopWatch.getLastTaskName());

// 任务总的耗时  如果你想获取到每个任务详情(包括它的任务名、耗时等等)可使用
System.out.println("所有任务总耗时:" + stopWatch.getTotalTimeMillis());
System.out.println("任务总数:" + stopWatch.getTaskCount());

三、Instant的使用

Instant start = Instant.now();
Thread.sleep(2000);
Instant end = Instant.now();
long duration = Duration.between(start, end).toMillis();
System.out.println("耗时:" + duration + "ms");