Java【StopWatch计算时间差】
以前在进行时间耗时时我们通常的做法是先给出计算前后两个的时间值,然后通过详见来计算耗时时长。
eg:
1 public static void main(String[] args) { 2 long start = System.currentTimeMillis(); 3 // ......业务处理 4 System.out.println("耗时:" + (System.currentTimeMillis() - start) + "ms"); 5 }
我们可以使用已有的工具类中的秒表来替代上述的使用方式,现有的秒表工具类有org.springframework.util.StopWatch、org.apache.commons.lang.time.StopWatch,这里以Spring的StopWatch类为例:
1 public class Test { 2 3 public static void main(String[] args) throws InterruptedException{ 4 StopWatch stopWatch = new StopWatch("任务耗时秒表工具"); 5 stopWatch.start("task1"); 6 Thread.sleep(1000); 7 stopWatch.stop();10 11 stopWatch.start("task2"); 12 Thread.sleep(3000); 13 stopWatch.stop(); 14 15 //所有任务耗时时间 16 System.out.println("当前任务总耗时: " + stopWatch.getTotalTimeMillis()); 17 System.out.println("当前任务各个阶段耗时: " + stopWatch.prettyPrint()); 18 } 19 }
打印结果
1 当前任务总耗时: 4000 2 当前任务各个阶段耗时: StopWatch '任务耗时秒表工具': running time = 4000217942 ns 3 --------------------------------------------- 4 ns % Task name 5 --------------------------------------------- 6 1000071540 025% task1 7 3000146402 075% task2