使用 StopWatch 统计任务时间

背景:
最近看springboot源码时发现springboot的任务计时是通过StopWatch来完成的,在此研究下该类的使用方法


一、SpringBoot源码中的StopWatch

这里写图片描述
这里写图片描述


二、StopWatch用法

我们按照以往传统的方法是这样给代码中的任务计时的:

long start = System.currentTimeMillis();
......
long end = System.currentTimeMillis();
System.out.println("任务耗时:" + (end - start));

但这样如果执行大量测试的话就很麻烦,并且不直观,如果想对执行的时间做进一步控制,则需要在程序中很多地方修改;

目前spring-framework提供了StopWatch类可以做类似任务执行时间控制,也就是封装了一个对开始时间,结束时间记录操作的Java类,具体使用如下:

package com.moerlong.aaa;

import org.springframework.util.StopWatch;

/**
 * @Author: yuanj
 * @CreateDate: 2018/6/19 23:29
 * @Version: 1.0
 */
public class TestStopWatch {
    private void test() throws InterruptedException {
        StopWatch sw = new StopWatch();

        sw.start("喝咖啡");
        Thread.sleep(1000);
        sw.stop();

        sw.start("写代码");
        Thread.sleep(2000);
        sw.stop();

        sw.start("睡觉");
        Thread.sleep(500);
        sw.stop();

        System.out.println("任务综合信息:" + sw.prettyPrint());

        System.out.println("总任务时间:" + sw.getTotalTimeMillis());

        System.out.println("最后一个任务的名称" + sw.getLastTaskName());

        System.out.println("任务数量:" + sw.getTaskCount());

        //sw.getTaskInfo()返回值为List[TaskInfo]
        for (StopWatch.TaskInfo t: sw.getTaskInfo()) {
            System.out.println(t.getTaskName() + " : " + t.getTimeMillis());
        }
    }


    public static void main(String[] args) throws InterruptedException {
        TestStopWatch testStopWatch = new TestStopWatch();
        testStopWatch.test();
    }
}

执行结果:
这里写图片描述


三、源码一览

这里写图片描述

可以看到,StopWatch 类封装了System.currentTimeMillis();
在同一个stopWatch对象中,将每次stop都存放在linklist中,在统计的时候,再取出输出。

猜你喜欢

转载自blog.csdn.net/abysscarry/article/details/80740584