本文主要是介绍Spring 计时器StopWatch,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
背景
在做开发的时候需要记录每个任务执行时间,或者记录一段代码执行时间,简单且粗暴的方法就是打印当前时间与执行完时间的差值,然后这样如果执行大量测试的话就很麻烦,并且不直观,如果想对执行的时间做进一步控制,则需要在程序中很多地方修改,目前spring-framework提供了一个StopWatch类可以做类似任务执行时间控制,也就是封装了一个对开始时间,结束时间记录操作的Java工具类。
实例代码
package cn.zzg.mybatisplus.controller;import cn.zzg.mybatisplus.entity.BaseProjectPO;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("/stopWatch")
public class StopWatchController {@GetMapping("/test")public void test() throws InterruptedException {StopWatch stopWatch = new StopWatch();stopWatch.start("getUp");Thread.sleep(2000);stopWatch.stop();stopWatch.start("washUp");Thread.sleep(4000);stopWatch.stop();stopWatch.start("closeDoor");Thread.sleep(60000);stopWatch.stop();System.out.println(stopWatch.prettyPrint());System.out.println(stopWatch.getTotalTimeMillis());System.out.println(stopWatch.getLastTaskName());System.out.println(stopWatch.getLastTaskInfo());System.out.println(stopWatch.getTaskCount());}}
运行结果
StopWatch '': running time (millis) = 66016
-----------------------------------------
ms % Task name
-----------------------------------------
02004 003% getUp
04001 006% washUp
60011 091% closeDoor66016
closeDoor
org.springframework.util.StopWatch$TaskInfo@7cdb0296
3
这篇关于Spring 计时器StopWatch的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!