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% 任务二

分析:

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

转载于:https://www.cnblogs.com/webwangbao/p/9229566.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值