StopWatch的用法总结

StopWatch 是 Spring 框架中的一个工具类,主要用于记录代码执行的时间,帮助我们进行性能分析。它提供了简单的接口来开始、停止、暂停、继续和重置计时,并且可以多次记录不同任务的时间。这里是一些常见的用法总结:

1. 创建和启动 StopWatch

StopWatch stopWatch = new StopWatch();
stopWatch.start("task1");  // 启动一个计时任务

2. 停止计时

stopWatch.stop();  // 停止当前计时

3. 记录多个任务

可以通过 start() 启动多个任务,然后逐一停止。

stopWatch.start("task1");
// 执行 task1 的代码...
stopWatch.stop();  // 停止 task1

stopWatch.start("task2");
// 执行 task2 的代码...
stopWatch.stop();  // 停止 task2

4. 获取计时结果

你可以通过 getTotalTimeMillis() 获取所有任务的总执行时间,或者通过 getTaskInfo() 获取各个任务的执行时间。

System.out.println("Total time: " + stopWatch.getTotalTimeMillis() + " ms");

for (StopWatch.TaskInfo taskInfo : stopWatch.getTaskInfo()) {
    System.out.println(taskInfo.getTaskName() + " took " + taskInfo.getTimeMillis() + " ms");
}

5. 暂停和继续计时

如果你希望暂停计时并稍后恢复计时,StopWatch 也支持暂停和继续。

stopWatch.start("task1");
// 执行 task1 的代码...
stopWatch.stop();

// 暂停后继续
stopWatch.start("task2");
// 执行 task2 的代码...
stopWatch.stop();

6. 重置计时

如果你想重新开始计时,调用 reset() 来重置 StopWatch

stopWatch.reset();  // 清除所有任务和计时

7. 打印计时信息

你可以通过 prettyPrint() 方法以友好的格式打印所有的计时信息。

System.out.println(stopWatch.prettyPrint());

示例代码

import org.springframework.util.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();

        // 计时任务1
        stopWatch.start("task1");
        try {
            Thread.sleep(500);  // 模拟任务1的执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopWatch.stop();

        // 计时任务2
        stopWatch.start("task2");
        try {
            Thread.sleep(300);  // 模拟任务2的执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopWatch.stop();

        // 打印结果
        System.out.println("Total time: " + stopWatch.getTotalTimeMillis() + " ms");
        for (StopWatch.TaskInfo taskInfo : stopWatch.getTaskInfo()) {
            System.out.println(taskInfo.getTaskName() + " took " + taskInfo.getTimeMillis() + " ms");
        }
    }
}

输出

Total time: 800 ms
task1 took 500 ms
task2 took 300 ms

总结

StopWatch 是一个非常方便的工具,特别适合于性能调优、记录代码段的执行时间。它可以帮助开发人员快速判断哪部分代码执行缓慢,从而进行优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值