首页 > 其他 > 详细

StopWatch的使用

时间:2020-07-02 09:24:41      阅读:49      评论:0      收藏:0      [点我收藏+]

过往记录程序中复杂或者耗时处理时常使用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三个版本,具体使用按情况选择。

StopWatch的使用

原文:https://www.cnblogs.com/silenceshining/p/13222389.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!