Spring 计时工具类 StopWatch
位于Spring的核心包
设计目标
- 验证程序性能, 记录过程耗时
- 隐藏System.currentTimeMillis()的使用提升代码可读性
特性
- 支持多任务计时
- 非线程安全
主要函数
方法 | 备注 |
---|---|
void start(String) | 开始一个任务&开始计时 |
void stop() | 结束一个任务&&记录任务执行时间 |
String shortSummary() | 获取总运行时间的一个简短描述 |
String prettyPrint() | 返回任务执行报告 |
TaskInfo[] getTaskInfo() | 获取任务详情,用于自定义报告 |
Demo
import org.springframework.util.StopWatch;
/**
* 测试计时器
* @date 2021/6/5 20:03
*/
public class StopWatchTest {
public static void main(String[] args) throws InterruptedException {
StopWatch watch = new StopWatch("测试任务");
// 任务一
watch.start("查询数据库");
Thread.sleep(1000);
watch.stop();
// 任务二
watch.start("查redis");
Thread.sleep(10);
watch.stop();
// 任务三
watch.start("查es");
Thread.sleep(600);
watch.stop();
// 获取一个简短报告
System.out.println("简报:" + watch.shortSummary());
// 自定义报告
System.out.println("Diy报告:");
StopWatch.TaskInfo[] taskInfo = watch.getTaskInfo();
for (StopWatch.TaskInfo info : taskInfo) {
System.out.println(info.getTaskName() + ":" + info.getTimeMillis() + ", " + info.getTimeSeconds() + ".s");
}
// 详细报告
System.out.println("");
System.out.println("报告明细:");
System.out.println(watch.prettyPrint());
}
}
控制台:
简报:StopWatch '测试任务': running time (millis) = 1610
Diy报告:
查询数据库:1000, 1.0.s
查redis:10, 0.01.s
查es:600, 0.6.s
报告明细:
StopWatch '测试任务': running time (millis) = 1610
-----------------------------------------
ms % Task name
-----------------------------------------
01000 062% 查询数据库
00010 001% 查redis
00600 037% 查es
Process finished with exit code 0