org.springframework.util.StopWatch类

本文通过一个具体的示例介绍了如何使用Spring Boot中的StopWatch类来测量代码块的执行时间。示例展示了如何开始、停止计时以及如何打印出详细的执行时间报告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:日常开发中,要打印出逻辑代码块的消耗时长,通常呢会在逻辑代码块前后打印出当前系统时间,并减法,来计算出消耗时长。在查看SpringBoot的源码的时候,发现Spring提供了有一个叫StopWatch的类。使用起来很方便。

package com.example.studySpringBoot;

import org.junit.Test;
import org.springframework.util.StopWatch;


public class TestSpringStopWatch {

    @Test
    public void goodMorning() throws InterruptedException {
        StopWatch stopWatch = new StopWatch("早上洗漱");
        stopWatch.start("起床");
        Thread.sleep(5000);
        stopWatch.stop();
        stopWatch.start("刷牙");
        Thread.sleep(1000);
        stopWatch.stop();
        stopWatch.start("洗脸");
        Thread.sleep(3000);
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }
}

打印出来的效果看起来也很舒服:

StopWatch '早上洗漱': running time (millis) = 9001
-----------------------------------------
ms     %     Task name
-----------------------------------------
05000  056%  起床
01000  011%  刷牙
03001  033%  洗脸



2025-07-11 09:54:15.937 ERROR 13820 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: An attempt was made to call a method that does not exist. The attempt was made from the following location: org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:210) The following method did not exist: 'org.springframework.util.StopWatch$TaskInfo org.springframework.util.StopWatch.lastTaskInfo()' The calling method's class, org.springframework.data.repository.config.RepositoryConfigurationDelegate, was loaded from the following location: jar:file:/C:/Users/20651/.m2/repository/org/springframework/data/spring-data-commons/3.2.0/spring-data-commons-3.2.0.jar!/org/springframework/data/repository/config/RepositoryConfigurationDelegate.class The called method's class, org.springframework.util.StopWatch, is available from the following locations: jar:file:/C:/Users/20651/.m2/repository/org/springframework/spring-core/5.3.33/spring-core-5.3.33.jar!/org/springframework/util/StopWatch.class The called method's class hierarchy was loaded from the following locations: org.springframework.util.StopWatch: file:/C:/Users/20651/.m2/repository/org/springframework/spring-core/5.3.33/spring-core-5.3.33.jar Action: Correct the classpath of your application so that it contains compatible versions of the classes org.springframework.data.repository.config.RepositoryConfigurationDelegate and org.springframework.util.StopWatch 进程已结束,退出代码为 1
最新发布
07-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值