当前位置:   article > 正文

Spring 计时器StopWatch

Spring 计时器StopWatch

背景

在做开发的时候需要记录每个任务执行时间,或者记录一段代码执行时间,简单且粗暴的方法就是打印当前时间与执行完时间的差值,然后这样如果执行大量测试的话就很麻烦,并且不直观,如果想对执行的时间做进一步控制,则需要在程序中很多地方修改,目前spring-framework提供了一个StopWatch类可以做类似任务执行时间控制,也就是封装了一个对开始时间,结束时间记录操作的Java工具类

实例代码

  1. package cn.zzg.mybatisplus.controller;
  2. import cn.zzg.mybatisplus.entity.BaseProjectPO;
  3. import org.springframework.util.StopWatch;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import java.util.List;
  8. @RestController
  9. @RequestMapping("/stopWatch")
  10. public class StopWatchController {
  11. @GetMapping("/test")
  12. public void test() throws InterruptedException {
  13. StopWatch stopWatch = new StopWatch();
  14. stopWatch.start("getUp");
  15. Thread.sleep(2000);
  16. stopWatch.stop();
  17. stopWatch.start("washUp");
  18. Thread.sleep(4000);
  19. stopWatch.stop();
  20. stopWatch.start("closeDoor");
  21. Thread.sleep(60000);
  22. stopWatch.stop();
  23. System.out.println(stopWatch.prettyPrint());
  24. System.out.println(stopWatch.getTotalTimeMillis());
  25. System.out.println(stopWatch.getLastTaskName());
  26. System.out.println(stopWatch.getLastTaskInfo());
  27. System.out.println(stopWatch.getTaskCount());
  28. }
  29. }

运行结果

  1. StopWatch '': running time (millis) = 66016
  2. -----------------------------------------
  3. ms % Task name
  4. -----------------------------------------
  5. 02004 003% getUp
  6. 04001 006% washUp
  7. 60011 091% closeDoor
  8. 66016
  9. closeDoor
  10. org.springframework.util.StopWatch$TaskInfo@7cdb0296
  11. 3

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号