StopWatch使用

来源

  1. 父类:Object
  2. 包名:org.springframework.util.StopWatch
  3. 线程安全:不安全,不可同步

测试

单任务测试

getTotalTimeMillis:获取总耗时,单位毫秒

getTotalTimeSeconds() :获取总耗时,单位秒

public class singleTest {  
  
    public static void main (String[] args) throws InterruptedException {  
        StopWatch sw = new StopWatch();  
        sw.start();  
        //doSomeThing  
        Thread.sleep(1000);  
        sw.stop();  
        System.out.println(sw.getTotalTimeMillis());  
    }  
}

返回:

1011

多任务测试

sw.prettyPrint():表格方式打印各个方法耗时

public class MuliTest {  
  
    public static void main (String[] args) throws InterruptedException {  
        StopWatch sw = new StopWatch();  
        sw.start("A方法");  
        Thread.sleep(500);  
        sw.stop();  
        sw.start("B方法");  
        Thread.sleep(300);  
        sw.stop();  
        sw.start("C方法");  
        Thread.sleep(200);  
        sw.stop();  
        System.out.println(sw.prettyPrint());  
    }  
}
StopWatch '': running time (millis) = 1031  
-----------------------------------------  
ms     %     Task name  
-----------------------------------------  
00514  050%  A方法  
00302  029%  B方法  
00215  021%  C方法

其他用法

不同的打印结果

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

实战使用

定位性能瓶颈

复杂业务场景中,一个流程可能会调用多方系统的接口,此时本系统的处理能力被各个接口性能所控制,打印各个接口原先使用starttime、endtime再相减计算,现在使用此类更加方便可提供表格汇总功能,更加直观!

打印关键日志

用于打印自己开发的方法的性能,更加方便使用,使得代码更加整洁

总结

​ StopWatch工具类大大提供了工作的效率,更加方便程序员快速撸代码!!!

参考资料

https://mp.weixin.qq.com/s/2ZTiWN5yp5sjjkOn8EQyNQ

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StopWatch.html

posted on 2022-11-02 11:10  探路_先锋  阅读(300)  评论(0编辑  收藏  举报
……