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%  closeDoor

66016
closeDoor
org.springframework.util.StopWatch$TaskInfo@7cdb0296
3
相关推荐
demo007x3 分钟前
在国内也能使用 Claude cli给自己提效,附实操方法
前端·后端·程序员
jayaccc12 分钟前
Webpack配置详解与实战指南
前端·webpack·node.js
南囝coding12 分钟前
发现一个宝藏图片对比工具!速度比 ImageMagick 快 6 倍,还是开源的
前端
华如锦17 分钟前
四:从零搭建一个RAG
java·开发语言·人工智能·python·机器学习·spring cloud·计算机视觉
Tony_yitao19 分钟前
22.华为OD机试真题:数组拼接(Java实现,100分通关)
java·算法·华为od·algorithm
前端小黑屋20 分钟前
查看 Base64 编码的字体包对应的字符集
前端·css·字体
JavaGuru_LiuYu20 分钟前
Spring Boot 整合 SSE(Server-Sent Events)
java·spring boot·后端·sse
爬山算法24 分钟前
Hibernate(26)什么是Hibernate的透明持久化?
java·后端·hibernate
彭于晏Yan26 分钟前
Springboot实现数据脱敏
java·spring boot·后端
每天吃饭的羊30 分钟前
媒体查询
开发语言·前端·javascript