Java skill - 统计耗时用StopWatch
Java skill系列目录:
【Java skill - 统计耗时用StopWatch】
【Java skill - 快速创建List、Map集合】
【Java skill - @JsonAlias 和 @JsonProperty】
StopWatch的使用
之前我们统计耗时都是用的System.currentTimeMillis,创建开始时间和结束时间两个变量,最终想减,这种方式既low,编写又繁琐。
之后,了解过springboot的启动源码之后,发下了StopWatch这个好用的统计耗时的类。
以下是Demo:
StopWatch sw = new StopWatch();
// 开始计时
sw.start("task1");
Thread.sleep(1000);
// 停止计时
sw.stop();
// 展示最后任务的耗时毫秒数
System.out.println(sw.getLastTaskTimeMillis());
// 再次开始计时
sw.start("task2");
Thread.sleep(2000);
// 停止计时
sw.stop();
// 展示最后任务的耗时毫秒数
System.out.println(sw.getLastTaskTimeMillis());
// 展示任务数和所有任务的总用时
System.out.format("%d,%s ",sw.getTaskCount(),sw.getTotalTimeSeconds());
System.out.println();
// 展示统计图表,包含任务名、任务耗时、耗时占比
System.out.println(sw.prettyPrint());