StopWatch 是 org.springframework.util包下面的一个工具类,通过这个可以对程序部分代码进行计时。适用于同步单线程代码块。
使用此工具比使用System.currentTimeMillis()来计算耗时等操作更方便一些。
使用方式如下:
public class StopWatchTest {
@Test
public void test() throws InterruptedException {
StopWatch stopWatch = new StopWatch("测试");
stopWatch.start("测试1");
TimeUnit.SECONDS.sleep(1);
stopWatch.stop();
stopWatch.start("测试2");
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
stopWatch.start("测试3");
TimeUnit.SECONDS.sleep(3);
stopWatch.stop();
// 获取某一个任务的耗时
StopWatch.TaskInfo[] taskInfo = stopWatch.getTaskInfo();
Arrays.stream(taskInfo).forEach(ti -> {
System.out.println(ti.getTimeMillis());
});
// 获取总体耗时
System.out.println(stopWatch.getTotalTimeMillis());
// 获取上一个任务的耗时
System.out.println(stopWatch.getLastTaskTimeMillis());
// 格式化输出
System.out.println(stopWatch.prettyPrint());
// 查看是否在运行中
System.out.println(stopWatch.isRunning());
}
}
输出:
1000
2001
3001
6004
3001
StopWatch '测试': running time = 6004158700 ns
---------------------------------------------
ns % Task name
---------------------------------------------
1000947000 017% 测试1
2001671900 033% 测试2
3001539800 050% 测试3
false
BUILD SUCCESSFUL in 13s
使用此工具可以记录服务的启动时间,如下所示:`
@SpringBootApplication
@EnableScheduling
@ComponentScan(value = "cn.ac.iscas.dmo.file.preview.*")
public class FilePreviewServer {
private static final Logger logger = LoggerFactory.getLogger(FilePreviewServer.class);
public static void main(String[] args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = new SpringApplicationBuilder(FilePreviewServer.class)
.logStartupInfo(false)
.run(args);
stopWatch.stop();
Integer port = context.getBean(ServerProperties.class).getPort();
logger.info("文件预览服务启动完成,耗时:{}s,演示页请访问: http://127.0.0.1:{} ", stopWatch.getTotalTimeSeconds(), port);
}
}