以前统计方法的运行时间经常会用
long startTime = System.currentTimeMillis();
// 业务实现
...
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime)
在 commons 包和 spring 中都提供了定时器,可以方便的统计方法的运行时间
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
示例代码
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Thread.sleep(1000);
// 断点
stopWatch.split();
System.out.println(stopWatch.getSplitTime());
// 断点
Thread.sleep(2000);
stopWatch.split();
// 获取运行了多长时间
System.out.println(stopWatch.getSplitTime());
// 暂停计时
stopWatch.suspend();
Thread.sleep(1000);
// 恢复计时
stopWatch.resume();
Thread.sleep(2000);
stopWatch.stop();
System.out.println(stopWatch.toString());