2022年9月2日
StopWatch
参考:别再用 System.currentTimeMillis 统计耗时了,太 Low,试试 Spring Boot 源码在用的 StopWatch吧,够优雅! – 掘金 (juejin.cn)
如果想要计算步骤的的耗时,通常可以打印两个时间的差值。这里提供一种方法,直接使用StopWatch工具类来处理
// 创建一个 StopWatch 实例
StopWatch sw = new StopWatch("沉默王二是傻 X");
// 开始计时
sw.start("任务1");
Thread.sleep(1000);
// 停止计时
sw.stop();
System.out.printf("任务1耗时:%d%s.\n", sw.getLastTaskTimeMillis(), "ms");
sw.start("任务2");
Thread.sleep(1100);
sw.stop();
System.out.printf("任务2耗时:%d%s.\n", sw.getLastTaskTimeMillis(), "ms");
System.out.printf("任务数量:%s,总耗时:%ss.\n", sw.getTaskCount(), sw.getTotalTimeSeconds());
另外,StopWatch 还提供了一个 sw.prettyPrint()
方法供打印出漂亮的格式化结果:
StopWatch '沉默王二是傻 X': running time = 2108529351 ns
---------------------------------------------
ns % Task name
---------------------------------------------
1004338467 048% 任务1
1104190884 052% 任务2
除此之外,还可以使用其他工具类,如hutool提供的StopWatch来实现类似功能,实际上内部还是使用nanotime来实现的,类似system.currentTimeMillis的一个封装。