为什么使用StopWatch
在项目中难免会遇到统计代码执行时间的需求,或者是自己想要看下某行/某些代码执行的时常,通常我们会这么做
@Test
public void testOld() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(3000);
long end = System.currentTimeMillis();
System.out.println("执行时间:" + (end - start));
}
但这样的代码写多了难免会烦。好在Spring等众多开源框架提供了一个类专门用于单线程的统计顺序执行代码的时常,他就是StopWatch,这里这介绍Spring版本的StopWatch
StopWatch使用方法
步骤:
- 创建定时器,起始就是
new一个对象咯 - 启动定时器,就是调用
start方法,start方法可以传递一个参数来表示当前启动的任务名称。 - 关闭定时器,就是调用
stop方法咯,该方法无参,无重载。 - 打印定时器执行任务的结果,调用
prettyPrint方法。还有其他API可以查看任务的其他信息。
Demo示例如下
public class StopWatchTest {
@Test
public void test1() throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start("task1");
Thread.sleep(3000);
stopWatch.stop();
stopWatch.start("task2");
Thread.sleep(2452);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
System.out.println(stopWatch.getLastTaskName()); // 最后一个任务的名称
System.out.println(stopWatch.currentTaskName()); // 当前任务名称
System.out.println(stopWatch.getTaskCount()); // 任务数量
System.out.println(stopWatch.getTotalTimeMillis()); // 获取任务总共的毫秒
System.out.println(stopWatch.getLastTaskTimeNanos()); // 获取任务总共执行的纳秒
System.out.println(stopWatch.getTotalTimeSeconds()); // 获取秒
}
}
输出结果
StopWatch '': running time = 5460650800 ns
---------------------------------------------
ns % Task name
---------------------------------------------
3008043900 055% task1
2452606900 045% task2
StopWatch '': running time = 5460650800 ns; [task1] took 3008043900 ns = 55%; [task2] took 2452606900 ns = 45%
task2
null
2
5460
2452606900
5.4606508
StopWatch注意事项
- 它并不线程安全,适合单线程使用
- 在一个任务开始后(也就是在一个任务调用start方法后)。执行下一个任务之前必须关闭上一个任务,否则会报错。换个说法就是调用一次
start方法后必须调用一次stop方法才能执行下一次start - 源码实现比较简单,可自行查看源码