spring StopWatch的使用

在查看代码执行时间时,我们常用System.currentTimeMillis()

long start = System.currentTimeMillis();
// 执行业务方法...
System.out.println("总耗时" + (System.currentTimeMillis() - start) + "(ms)");

spring 提供了一种简便的方式

1.StopWatch使用示例

public class TestStopwatch {
    // 业务方法一
    public static void execBusinessMethod1() throws InterruptedException {
        Thread.sleep(100);
        System.out.println(">>>>>>>>>>>>执行业务方法一<<<<<<<<<<<<<<<");
    }

    // 业务方法二
    public static void execBusinessMethod2() throws InterruptedException {
        Thread.sleep(200);
        System.out.println(">>>>>>>>>>>>执行业务方法二<<<<<<<<<<<<<<<");
    }

    // 演示
    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch();

        stopWatch.start("方法一");
        execBusinessMethod1();
        stopWatch.stop();

        stopWatch.start("方法二");
        execBusinessMethod2();
        stopWatch.stop();

        stopWatch.start("代码块一");
        for (int i = 0; i < 1000; ) {
            i++;
        }
        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint()); // 美化输出
        System.out.println("总耗时: " + stopWatch.getTotalTimeSeconds() + "(s)"); // 获取秒为单位的总耗时
    }
}

2.StopWatch执行结果

>>>>>>>>>>>>执行业务方法一<<<<<<<<<<<<<<<
>>>>>>>>>>>>执行业务方法二<<<<<<<<<<<<<<<
StopWatch '': running time = 321757500 ns
---------------------------------------------
ns         %     Task name
---------------------------------------------
113107100  035%  方法一
208644500  065%  方法二
000005900  000%  代码块一

总耗时: 0.3217575(s)

3.StopWatch使用总结

  • StopWatch只作为调试代码的工具 相较于System.currentTimeMillis()简便一些,有格式化的统一输出;

  • StopWatch实例一次只能start一个task,不能同时start多个task;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值