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 com.springDemodemo;

import org.springframework.util.StopWatch;

public class StopWatchDemo {

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("业务A");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopWatch.stop();
        stopWatch.start("业务B");
        long startB = System.currentTimeMillis();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());

    }
}

打印结果如下:

topWatch '': running time = 5004619200 ns
---------------------------------------------
ns % Task name
---------------------------------------------
1997837800 040% 业务A
3006781400 060% 业务B

可以看出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三个版本,具体使用按情况选择。

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