比system.currentTimeMillis还要好用的统计耗时方法stopWatch

文章目录


我们在开发中通常用 system.currentTimeMillis来统计每个任务的耗时,或者记录一段时间执行的时间,但是在 spirngboot源码中用到了 stopWatch来统计耗时的方法,非常简介,好用。

引入jar包-如果是SpringBoot项目就不需要再去引入jar包

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
</dependency>

springBoot的xml里面有如下jar包

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

在多任务的情况下,StopWatch的好处就能完全体现出来

单个任务示例

public class Test {
    public static void main(String[] args) throws InterruptedException {
        //创建一个StopWatch对象
        StopWatch stopWatch=new StopWatch();
        //开始计时
        stopWatch.start();
        //睡眠
        Thread.sleep(1000);
        //结束计时
        stopWatch.stop();
        //打印耗时总时长
        System.out.println("耗时:"+stopWatch.getTotalTimeMillis()+"毫秒");
        //获取总耗时单位是秒
        System.out.println("总耗时:"+stopWatch.getTotalTimeSeconds()+"秒");
    }
}

耗时:986毫秒
总耗时:0.9865676秒

多个任务示例

public class Test {
    public static void main(String[] args) throws InterruptedException {
  		//创建一个StopWatch对象
        StopWatch stopWatch=new StopWatch();
        //开始计时
        stopWatch.start("吃饭");
        //睡眠
        Thread.sleep(1000);
        //结束计时
        stopWatch.stop();
        //打印耗时时长单位毫秒
        System.out.println("吃饭耗时:"+stopWatch.getTotalTimeMillis()+"毫秒");
        //开始计时
        stopWatch.start("睡觉");
        //睡眠
        Thread.sleep(2000);
        //结束计时
        stopWatch.stop();
        //打印耗时时长单位毫秒
        System.out.println("睡觉耗时:"+stopWatch.getTotalTimeMillis()+"毫秒");
        //打印两个任务各占多少时长
        System.out.println(stopWatch.prettyPrint());
        //获取总耗时单位是秒
        System.out.println("总耗时:"+stopWatch.getTotalTimeSeconds()+"秒");
    }
}

在这里插入图片描述

操作十分简单,一学就会,难道你还学不会?

  • 先 new 一个StopWatch 对象
  • 再 start 开始计时
  • 然后 stop 停止计时
  • 通过 stopWatch.getTotalTimeMillis() 得出单个任务耗时
  • 最后通过stopWatch.getTotalTimeSeconds() 获取总耗时

StopWatch还有一些其他的方法可以使用

prettyPrint:用自带格式输出所有任务信息。
getTaskInfo:获取所有任务的信息,即各个任务的名称和耗时。(如果想自定义输出一些内容,或者格式,可以从这里获取所有任务的信息)
getTotalTimeMillis:获取任务总耗时(毫秒)。
getTotalTimeSeconds:获取任务总耗时(秒)。
getTaskCount:获取任务总数。
getLastTaskName:获取最后一个任务的名称。
getLastTaskTimeMillis:获取最后一个任务的耗时(毫秒)。
getLastTaskInfo:获取最后一个任务的信息,即任务的名称和耗时。


如果对你有所帮助,感谢点赞支持,谢谢

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值