Spring 计时工具类 StopWatch

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
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值