有时我们在做开发的时候需要记录每个任务执行时间,或者记录一段代码执行时间,一般我们检测某段代码执行的时间,都是以下方式来进行的:
long start = System.currentTimeMillis();
new Random(); // 耗时操作
long end = System.currentTimeMillis();
System.out.println(end-start);

有一说一,太不优雅了

StopWatch实现
事实上spring自带了秒表工具类: org.springframework.util.StopWatch
还有apache大佬也有对应的工具类:org.apache.commons.lang.time.StopWatch

直接看如何使用:
spring 版
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();

// 任务一模拟休眠3秒钟
stopWatch.start("TaskOneName");
Thread.sleep(1000 * 3);
System.out.println("当前任务名称:" + stopWatch.currentTaskName());
stopWatch.stop();

// 任务一模拟休眠10秒钟
stopWatch.start("TaskTwoName");
Thread.sleep(1000 * 10);
System.out.println("当前任务名称:" + stopWatch.currentTaskName());
stopWatch.stop();

// 任务一模拟休眠10秒钟
stopWatch.start("TaskThreeName");
Thread.sleep(1000 * 10);
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.getLastTaskInfo());

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

}
apache 版
public static void main(String[] args) throws InterruptedException {
//创建后立即start,常用
StopWatch watch = StopWatch.createStarted();

// StopWatch watch = new StopWatch();
// watch.start();

Thread.sleep(1000);
System.out.println(watch.getTime());
System.out.println("统计从开始到现在运行时间:" + watch.getTime() + "ms");

Thread.sleep(1000);
watch.split();
System.out.println("从start到此刻为止的时间:" + watch.getTime());
System.out.println("从开始到第一个切入点运行时间:" + watch.getSplitTime());


Thread.sleep(1000);
watch.split();
System.out.println("从开始到第二个切入点运行时间:" + watch.getSplitTime());

// 复位后, 重新计时
watch.reset();
watch.start();
Thread.sleep(1000);
System.out.println("重新开始后到当前运行时间是:" + watch.getTime());

// 暂停 与 恢复
watch.suspend();
System.out.println("暂停2秒钟");
Thread.sleep(2000);

// 上面suspend,这里要想重新统计,需要恢复一下
watch.resume();
System.out.println("恢复后执行的时间是:" + watch.getTime());

Thread.sleep(1000);
watch.stop();

System.out.println("花费的时间》》" + watch.getTime() + "ms");
// 直接转成s
System.out.println("花费的时间》》" + watch.getTime(TimeUnit.SECONDS) + "s");

}
[参考链接]:https://www.jb51.net/article/233720.htm