springframework中的StopWatch的用法

本文介绍了Spring框架中秒表工具StopWatch的使用方法。通过示例代码展示了如何记录多个任务的执行时间,并使用prettyPrint方法以友好格式输出总耗时及各任务耗时占比。

StopWatch对应的中文名称为秒表,经常我们对一段代码耗时检测的代码如下:

long startTime = System.currentTimeMillis();
// 你的业务代码
long endTime = System.currentTimeMillis();
long costTime = endTime -startTime;
System.err.println("该段代码耗时:" + costTime + " ms");
改进的代码写法:
我们可以利用已有的工具类中的秒表,常见的秒表工具类有org.springframework.util.StopWatch、org.apache.commons.lang.time.StopWatch以及谷歌提供的guava中的秒表(这个我没怎么用过)。这里重点讲下,org.springframework.util.StopWatch的用法。
org.springframework.util.StopWatch的用法:
查看其源码:
public class StopWatch {
    private final String id;
    private boolean keepTaskList;
    private final List<StopWatch.TaskInfo> taskList;
    private long startTimeMillis;
    private boolean running;
    private String currentTaskName;
    private StopWatch.TaskInfo lastTaskInfo;
    private int taskCount;
    private long totalTimeMillis;
     ...
}
可以看到有一个List<StopWatch.TaskInfo> taskList,用于存储一组任务的耗时时间。这个很有用比如:我们可以记录多段代码耗时时间,然后一次性打印(这里:org.springframework.util.StopWatch提供了一个prettyString()函数用于按照指定格式打印出耗时)
举个例子:
public static void main(String[] args) throws InterruptedException {
    // 定义一个计数器
    StopWatch stopWatch = new StopWatch("统一一组任务耗时");
    // 统计任务一耗时
    stopWatch.start("任务一");
    Thread.sleep(1000);
    stopWatch.stop();

    // 统计任务二耗时
    stopWatch.start("任务二");
    Thread.sleep(2000);
    stopWatch.stop();

    // 打印出耗时
    String result = stopWatch.prettyPrint();
    System.err.println(result);
}
结果为:
StopWatch '统一一组任务耗时': running time (millis) = 3000
-----------------------------------------
ms % Task name
-----------------------------------------
01000 033% 任务一
02000 067% 任务二
分析:
可以看到可以统一定义一个计数器为“统一一组任务耗时”,然后看到整段代码的耗时。以及各个部分程序代码的执行时间,并且输出的格式帮我们整理好了。
### 关于 `org.springframework.util.StopWatch` 的功能与用法 #### 功能概述 `org.springframework.util.StopWatch` 是 Spring 框架中的一个实用工具类,用于测量代码片段的执行时间。它提供了一种简单而有效的方式来跟踪多个任务的时间消耗,并能够生成详细的性能报告[^2]。 #### 基本特性 - **多任务支持**:可以同时监控多个任务的运行时间。 - **友好的输出格式**:通过 `prettyPrint()` 方法生成易于阅读的任务耗时报告[^5]。 - **精确到毫秒级**:默认情况下,StopWatch 提供毫秒级别的精度[^4]。 --- #### 使用方法 以下是 `StopWatch` 类的基本使用流程: 1. **创建实例** 需要先创建一个 `StopWatch` 对象。 2. **启动计时器** 调用 `start(String taskName)` 或者 `start()` 开始计时。如果指定了任务名称,则该次计时会被标记为此任务名。 3. **执行目标代码** 执行需要被测量耗时的代码逻辑。 4. **停止计时器** 调用 `stop()` 结束当前任务的计时。 5. **获取统计数据** 可以通过多种方式获取统计信息: - 获取单个任务的耗时:`getLastTaskTimeMillis()` - 获取总耗时:`.getTotalTimeMillis()` - 获取所有任务的详细列表:`getTaskList()` 6. **重置计时器** 如果需要重新开始新的计时周期,可以通过调用 `reset()` 清除之前的记录数据[^3]。 --- #### 实战代码示例 下面是一个完整的代码示例展示如何使用 `StopWatch` 测量不同任务的执行时间: ```java import org.springframework.util.StopWatch; public class StopWatchExample { public static void main(String[] args) { // 创建一个新的 StopWatch 实例 StopWatch stopWatch = new StopWatch(); // 启动第一个任务计时 stopWatch.start("加载配置"); try { Thread.sleep(100); // 模拟加载配置所需时间 } catch (InterruptedException e) { e.printStackTrace(); } stopWatch.stop(); // 停止第一个任务计时 // 启动第二个任务计时 stopWatch.start("处理业务逻辑"); try { Thread.sleep(200); // 模拟处理业务逻辑所需时间 } catch (InterruptedException e) { e.printStackTrace(); } stopWatch.stop(); // 停止第二个任务计时 // 输出友好的性能报告 System.out.println(stopWatch.prettyPrint()); } } ``` 上述代码会输出如下形式的结果: ``` StopWatch '': running time (millis) = 300 ----------------------------------------- ms % Task name ----------------------------------------- 0100 33% 加载配置 0200 67% 处理业务逻辑 ``` --- #### 注意事项 - **线程安全性**:`StopWatch` 并不是线程安全的,因此不建议在多线程环境中共享同一个实例。 - **高精度需求**:对于纳秒级别或者更高精度的需求,可能需要考虑其他更专业的性能分析工具或 API。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值