说明
在我们的实际开发中,多多少少会遇到统计一段代码片段的耗时的情况,下面分享本人常用的方法。
第一步,在pom.xml加入依赖,如下
<!-- StopWatch耗时计算 -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
第二步,创建并编写Time类,运行main方法查看效果,如下
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.StopWatch;
@Slf4j
public class Time {
public static void main(String[] args) throws Exception {
log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
test1();
log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
/**
* 耗时计算
*/
public static void test1() throws Exception {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Thread.sleep(5000);
stopWatch.stop();
log.info("耗时计算:{}", (double) stopWatch.getTime()/1000 + "s");
// 重新开始计算
stopWatch.reset();
stopWatch.start();
Thread.sleep(3000);
stopWatch.stop();
log.info("耗时计算:{}", (double) stopWatch.getTime()/1000 + "s");
}
}