Spring框架中stopwatch(秒表)

StopWatch对应的中文名称为秒表,经常我们对一段代码耗时检测的代码如下:

long startTime = System.currentTimeMillis();

// 你的业务代码

long endTime = System.currentTimeMillis();

long costTime = endTime -startTime;

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

改进的代码写法:

我们可以利用已有的工具类中的秒表,常见的秒表工具类有org.springframework.util.StopWatch、org.apache.commons.lang.time.StopWatch以及谷歌提供的guava中的秒表(这个我没怎么用过)。这里重点讲下,org.springframework.util.StopWatch的用法。

org.springframework.util.StopWatch的用法:

查看其源码:

public class StopWatch {

private final String id;

private boolean keepTaskList;

private final List<StopWatch.TaskInfo> taskList;

private long startTimeMillis;

private boolean running;

private String currentTaskName;

private StopWatch.TaskInfo lastTaskInfo;

private int taskCount;

private long totalTimeMillis;

...

}

可以看到有一个List<StopWatch.TaskInfo> taskList,用于存储一组任务的耗时时间。这个很有用比如:我们可以记录多段代码耗时时间,然后一次性打印(这里:org.springframework.util.StopWatch提供了一个prettyString()函数用于按照指定格式打印出耗时)

举个例子:

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);

}

结果为:

StopWatch '统一一组任务耗时': running time (millis) = 3000

-----------------------------------------

ms % Task name

-----------------------------------------

01000 033% 任务一

02000 067% 任务二

分析:

可以看到可以统一定义一个计数器为“统一一组任务耗时”,然后看到整段代码的耗时。以及各个部分程序代码的执行时间,并且输出的格式帮我们整理好了。

猜你喜欢

转载自www.cnblogs.com/webwangbao/p/9229566.html
今日推荐