传统方法:
Long startTime = System.currentTimeMillis();
//业务代码
Long endTime = System.currentTimeMillis();
Long elapsedTime = endTime - startTime;
System.out.println("该段总共耗时:" + elapsedTime + "ms");
使用
StopWath实现:
首先需要引入依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
具体使用方法:
//创建后立即start
StopWatch watch = StopWatch.createStarted();
Thread.sleep(800);
System.out.println("开始到现在运行时间:" + watch.getTime() + "ms");//800ms
Thread.sleep(1000);
System.out.println("从start到此刻为止的时间:" + watch.getTime());//1800
// 复位后, 重新计时
watch.reset();
watch.start();
Thread.sleep(1000);
System.out.println("重新开始后到当前运行时间是:" + watch.getTime());//1000
个人感觉使用StopWatch计时更加优雅一些。