• Spring计时器StopWatch使用


    在项目中,我们一般需要看一段处理逻辑的运行时间,之前写法如下:

        public void oldTest() throws Exception{
            long start = System.currentTimeMillis();
            Thread.sleep(new Double(Math.random()*1000).longValue());
            long stop = System.currentTimeMillis();
            long start1 = System.currentTimeMillis();
            Thread.sleep(new Double(Math.random()*1000).longValue());
            long stop1 = System.currentTimeMillis();
            log.info("测试使用时间=={}", stop - start);
            log.info("测试使用时间1=={}", stop1 - start1);
        }

    输出结果:

    ‘这样写非常简单有效,但是写的多了就会比较烦,且输出不够直观,然后看下Spring提供的工具类  StopWatch

        public void newTest() throws Exception{
            StopWatch sw = new StopWatch("newTest");
            sw.start("test1");
            Thread.sleep(new Double(Math.random()*1000).longValue());
            sw.stop();
            sw.start("test2");
            Thread.sleep(new Double(Math.random()*1000).longValue());
            sw.stop();
            log.info("sw.prettyPrint()===={}" ,sw.prettyPrint());
            log.info("sw.shortSummary()===={}" ,sw.shortSummary());
        }

    输出结果:

     通过输出会发现,使用prettyPrint可以打印每一个环节使用的时间及所占用时比例。

    然后就是看一下StopWatch优缺点了

      优点: spring自带工具类,可直接使用 代码实现简单,使用更简单 统一归纳,展示每项任务耗时与占用总时间的百分比,展示结果直观 性能消耗相对较小,并且最大程度的保证了start与stop之间的时间记录的准确性 可在start时直接指定任务名字,从而更加直观的显示记录结果

      缺点: 一个StopWatch实例一次只能开启一个task,不能同时start多个task,并且在该task未stop之前不能start一个新的task,必须在该task stop之后才能开启新的task,若要一次开启多个,需要new不同的StopWatch实例 代码侵入式使用,需要改动多处代码

  • 相关阅读:
    Office2010中功能强大的图片背景删除工具
    ArcGIS 缓冲区单位转换问题
    ArcGIS Server 优化
    SQLSERVER 三值逻辑
    SQLSERVER 重置自增列
    ArcGIS 基于AO 实现的经纬度定位
    AO连接ArcGIS server 超时问题
    MySQL 1064 错误
    Socket 请求http 汉字编码问题
    Navicat创建存储过程
  • 原文地址:https://www.cnblogs.com/liconglong/p/13713149.html
Copyright © 2020-2023  润新知