Spring计时器StopWatch的简单使用

最近新学了一个代码计时方法StopWatch替代繁琐的System.currentTimeMillis()计时,常见的工具类有org.springframework.util.StopWatch、org.apache.commons.lang3.time.StopWatch。(前者支持多任务执行时间统计,后者适用单任务计时)

1.org.springframework.util.StopWatch

源码解析:

public class StopWatch {

   /**
    * Identifier of this stop watch.
    * Handy when we have output from multiple stop watches
    * and need to distinguish between them in log or console output.
    */
   private final String id;

   private boolean keepTaskList = true;

   private final List<TaskInfo> taskList = new LinkedList<>();

   /** Start time of the current task */
   private long startTimeMillis;

   /** Name of the current task */
   @Nullable
   private String currentTaskName;

   @Nullable
   private TaskInfo lastTaskInfo;

   private int taskCount;

   /** Total running time */
   private long totalTimeMillis;

...

可以看到源码中的 List<TaskInfo> taskList,用于存储一组任务的耗时时间。

比如:

// 定义一个计时器

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) = 3004
-----------------------------------------
ms     %     Task name
-----------------------------------------
01003  033%  任务一
02001  067%  任务二
 

2.org.apache.commons.lang3.time.StopWatch

// 统计执行时间
StopWatch duration = new StopWatch();
duration.start();

//任务
Thread.sleep(2000);

duration.stop();
System.err.println(duration.getTime(TimeUnit.MILLISECONDS));

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值