今天分享的是Spring框架中的一个工具类,可以说成是一个计时器吧。如有不足,敬请指正。
一、传统计时方式
我们之前比如统计一个方法执行的时间通常都是:
long startTime = System.currentTimeMillis();
// 业务代码
long endTime = System.currentTimeMillis();
long costTime = endTime -startTime;
System.err.println("该段代码耗时:" + costTime + " ms");
二、使用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);
}
}
运行结果如下:
版权说明:欢迎以任何方式进行转载,但请在转载后注明出处!