使用Spring的StopWatch类优雅打印方法执行耗时

在做开发的时需要统计每个方法的执行消耗时间,或者记录一段代码执行时间,最简单的方法就是打印当前时间与执行完时间的差值,然后这样如果执行大量测试的话就很麻烦,并且不直观,然而使用使用Spring的StopWatch类就可以优雅打印方法执行耗时间

简单的Demo

复制代码
import org.springframework.util.StopWatch;  
  
public class SpringStopWatchExample {  
  
    public static void main (String[] args) throws InterruptedException {  
        StopWatch sw = new StopWatch();  
        sw.start();  
        //long task simulation  
        Thread.sleep(1000);  
        sw.stop();  
        System.out.println(sw.getTotalTimeMillis());  
    }  
}

打印同个方法多个代码块的执行消耗时间

复制代码
复制代码
import org.springframework.util.StopWatch;  
  
public class SpringStopWatchExample2 {  
  
    public static void main (String[] args) throws InterruptedException {  
        StopWatch sw = new StopWatch();  
        sw.start("A");  
        Thread.sleep(1000);  
        sw.stop();  
        sw.start("B");  
        Thread.sleep(200);  
        sw.stop();  
        sw.start("C");  
        Thread.sleep(500);  
        sw.stop();  
        System.out.println(sw.prettyPrint());  
    }  
}

输入结果

复制代码
StopWatch '': running time (millis) = 1031  
-----------------------------------------  
ms     %     Task name  
-----------------------------------------  
00514  100%   A  
00302  0200%  B  
00215  0500%  C

StopWatch常用方法
getTotalTimeSeconds() 获取总耗时秒,同时也有获取毫秒的方法
prettyPrint() 优雅的格式打印结果,表格形式
shortSummary() 返回简短的总耗时描述
getTaskCount() 返回统计时间任务的数量
getLastTaskInfo().getTaskName() 返回最后一个任务TaskInfo对象的名称

相关推荐
电魂泡哥5 小时前
SQL出现filesort 一定慢吗
数据库·sql
muddjsv7 小时前
大中小型企业数据层配置规模分析与选型指南
数据库
Runawayliquor7 小时前
opbase:CANN 所有算子的公共地基
大数据·数据库·人工智能·算法
yangshicong8 小时前
第11章:结构化输出与数据提取 —— 让 AI 直接返回你想要的数据格式
数据库·人工智能·redis·python·langchain·ai编程
chimchim668 小时前
pg dblink使用查询
数据库
Java面试题总结8 小时前
java高频面试题(2026最新)
java·开发语言·jvm·数据库·spring·缓存
苦逼的猿宝9 小时前
学生心理咨询评估系统
java·毕业设计·springboot·计算机毕业设计
隔窗听雨眠9 小时前
doctype、charset、meta如何控制整个渲染流水线
java·服务器·前端
绝知此事9 小时前
【算法突围 02】树形结构与数据库索引:树形结构与数据库索引:从 BST 到 B+ 树的演化与 MySQL 优化
数据库·mysql·算法·面试·b+树
牧羊狼的狼9 小时前
浅谈电商下单微服务流程
spring·spring cloud·微服务