ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Spring 计时器StopWatch

2026/8/15 2:35:40 拓冰建站 浏览量
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