Spring框架中的stopWatch


  今天分享的是Spring框架中的一个工具类,能够说成是一个计时器吧。若有不足,敬请指正。java

1、传统计时方式

  咱们以前好比统计一个方法执行的时间一般都是:spring

long startTime = System.currentTimeMillis();

// 业务代码

long endTime = System.currentTimeMillis();

long costTime = endTime -startTime;

System.err.println("该段代码耗时:" + costTime + " ms");

2、使用stopWatch

  咱们在使用Spring自带的工具类后能够很方便的计算出任务的耗时,直接上代码框架

package com.rrs.ktransfer.milkytea.test;

import com.rrss.ktransfer.milkytea.MilkyTeaApplication;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StopWatch;

/**
 * Created by lzx on 2019/8/17.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MilkyTeaApplication.class)
public class StopWatchTest {

    public static void main(String[] args) throws InterruptedException {

        StopWatch stopWatch = new StopWatch("统计一组任务耗时");

        // 统计任务一耗时

        stopWatch.start("任务一");

        Thread.sleep(1000);

        stopWatch.stop();


        // 统计任务二耗时

        stopWatch.start("任务二");

        Thread.sleep(2000);

        stopWatch.stop();

        // 打印出耗时

        String result = stopWatch.prettyPrint();

        System.err.println(result);
    }

}
运行结果以下:

版权说明:欢迎以任何方式进行转载,但请在转载后注明出处!工具

相关文章
相关标签/搜索