StopWatch的使用

过往记录程序中复杂或者耗时处理时常使用System.currentTimeMillis();,倒也能实现功能,但太繁琐,此处对比传统方式,以及使用StopWatch方式记录程序运行时间。有工具一定要用,能提高开发效率,摆脱繁琐的代码。

一 传统方式的处理

package test;

import org.springframework.util.StopWatch;

public class StopWatchDemo {

    public static void main(String[] args) {
        long startA = System.currentTimeMillis();
        System.out.println("业务A");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endA = System.currentTimeMillis();
        System.out.println("耗时:" + (endA - startA));

        long startB = System.currentTimeMillis();
        System.out.println("业务B");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endB = System.currentTimeMillis();
        System.out.println("耗时:" + (endB - startB));

    }
}

打印结果如下:

业务A
耗时:2003
业务B
耗时:3004

二 使用StopWatch的情况

package test;

import org.springframework.util.StopWatch;

public class StopWatchDemo {

    public static void main(String[] args) {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start("业务A");
        System.out.println("业务A");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopWatch.stop();
        System.out.println("耗时:" + stopWatch.getTotalTimeMillis());

        stopWatch.start("业务B");
        System.out.println("业务B");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopWatch.stop();
        System.out.println("耗时:" + stopWatch.getTotalTimeMillis());

        System.out.println(stopWatch.prettyPrint());
        System.out.println("总耗时" + stopWatch.getTotalTimeMillis());

    }
}

打印结果如下:

业务A
耗时:2003
业务B
耗时:5004
StopWatch '': running time (millis) = 5004
-----------------------------------------
ms     %     Task name
-----------------------------------------
02003  040%  业务A
03001  060%  业务B

总耗时5004

可以看出StopWatch对于记录程序运行时间提供了多个api,方便按任务(比如业务A B)进行时间统计,并提供整个运行过程的概览(最后的统计部分)。总结来说我们也可以使用基础的java api封装出类似的功能,但已有轮子,就没必要重复造了

三 StopWatch介绍

上述使用的是来自spring(org.springframework.util.StopWatch)的StopWatch;另外还有在common(org.apache.commons.lang3.time)包以及guava(com.google.common.base)包中都有StopWatch实现,但其实原理都类似。而且对于工具类的东西,一般都有spring,apache common,guava三个版本,具体使用按情况选择。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值