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实例 代码侵入式使用,需要改动多处代码

原文地址:https://www.cnblogs.com/liconglong/p/13713149.html