如何使用SpringBoot里面的StopWatch统计耗时

目录

一 、StopWatch 简介

二、StopWatch使用 

三、单个线程使用StopWatch要多次计算执行时间 


一 、StopWatch 简介

StopWatch:秒表,跑表的意思,我们按字面意思大概就可以推测出它是用来计算时间,监控时间之类的。允许多个任务的计时,暴露每个命名任务的总运行时间和运行时间。隐藏使用System.currentTimeMillis(),提高应用程序代码的可读性并减少计算错误的可能性

二、StopWatch使用 

  • 一般在开发工程中,我们统计代码运行耗时都是通过自己敲代码来完成的,例如下面代码
  public static void main(String[] args) throws InterruptedException {
       long start = System.currentTimeMillis();
       Thread.sleep(2000);
       System.out.println(System.currentTimeMillis()-start);
    }
  •  用StopWatch后,我们可以这样写,如代码:
    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Thread.sleep(2000);
        stopWatch.stop();
        System.out.println(stopWatch.getTotalTimeMillis());
    }
  • 以优雅的格式打出所有任务的耗时以及占比

 public static void main(String[] args) throws InterruptedException {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            Thread.sleep(2000);
            stopWatch.stop();
            System.out.println(stopWatch.prettyPrint());
        }
  • getTotalTimeSeconds() 获取总耗时秒,同时也有获取毫秒的方法

  • prettyPrint() 优雅的格式打印结果,表格形式

  • shortSummary() 返回简短的总耗时描述

  • getTaskCount() 返回统计时间任务的数量

  • getLastTaskInfo().getTaskName() 返回最后一个任务TaskInfo对象的名称

三、单个线程使用StopWatch要多次计算执行时间 

如果在单个线程我们要多次计算执行时间,那么StopWatch工具就更方便了,如下例子:

public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        for (int i = 0; i < 5; i++) {
            stopWatch.start("stopWatch"+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stopWatch.stop();
        }
        System.out.println("stopWatch task count :"+stopWatch.getTaskCount());
        System.out.println("总耗时:"+stopWatch.getTotalTimeSeconds()+"秒");
        for (StopWatch.TaskInfo taskInfo : stopWatch.getTaskInfo()) {
            System.out.println(taskInfo.getTaskName()+"耗时:"+taskInfo.getTimeSeconds()+"秒");
        }
    }

打印结果如下:
stopWatch task count :5
总耗时:5.0263041秒
stopWatch0耗时:0.9979452秒
stopWatch1耗时:1.0050517秒
stopWatch2耗时:1.0095104秒
stopWatch3耗时:1.0084876秒
stopWatch4耗时:1.0053092秒

扩展:当前 apache 工具包commons-lang3 也有 StopWatch 里面提供了更多的方法可供使用。比如,suspend 方法暂停计时、resume 方法恢复计时、reset 重新计时。

总结:StopWatch 的内部是通过 System.nanoTime() 来计时的,其实和 System.currentTimeMillis() 差别并不大。只不过nanoTime 比 currentTimeMillis 的粒度更细,前者是以纳秒为单位,后者是以毫秒为单位。

        

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

境里婆娑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值