zoukankan      html  css  js  c++  java
  • Spring计时器StopWatch使用

    我们可以利用已有的工具类中的秒表,常见的秒表工具类有org.springframework.util.StopWatch、org.apache.commons.lang.time.StopWatch以及谷歌提供的guava中的秒表。

    下面用Spring的StopWatch演示下耗时统计及打印的功能:

        public static void main(String[] args) {
            StopWatch sw = new StopWatch("test");
            try {
                //启动任务一
                sw.start("任务一");
                TimeUnit.SECONDS.sleep(1);
                sw.stop();
                
                //启动任务二
                sw.start("任务二");
                TimeUnit.SECONDS.sleep(3);
                sw.stop();
                System.out.println(sw.prettyPrint());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    结果打印:

    StopWatch 'test': running time (millis) = 4006
    -----------------------------------------
    ms     %     Task name
    -----------------------------------------
    01006  025%  任务一
    03000  075%  任务二

    start开始记录,stop停止记录,然后通过StopWatch的prettyPrint方法,可直观的输出代码执行耗时,以及执行时间百分比。

    其实以上内容在该工具类中实现也极其简单,通过start与stop方法分别记录开始时间与结束时间,其中在记录结束时间时,会维护一个链表类型的tasklist属性,从而使该类可记录多个任务,最后的输出也仅仅是对之前记录的信息做了一个统一的归纳输出,从而使结果更加直观的展示出来。

    StopWatch优缺点:

    优点:

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

    缺点:

    • 一个StopWatch实例一次只能开启一个task,不能同时start多个task,并且在该task未stop之前不能start一个新的task,必须在该task stop之后才能开启新的task,若要一次开启多个,需要new不同的StopWatch实例。
    • 代码侵入式使用,需要改动多处代码
  • 相关阅读:
    算法训练 数位分离
    算法训练 薪水计算
    算法训练 整除问题
    算法训练 数对
    pom.xml一个简单配置
    MyBatis3.4.0以上的分页插件错误:Could not find method on interface org.apache.ibatis.executor.statement.StatementHandler named prepare. Cause: java.lang.NoSuchMethodException: org.apache.ibatis.executor.stateme
    MyBatis3-实现MyBatis分页
    mybatis 易百练习笔记
    maven pom.xml配置
    Description Resource Path Location Type The superclass "javax.servlet.http.HttpServlet" was not foun
  • 原文地址:https://www.cnblogs.com/duanxz/p/5426774.html
Copyright © 2011-2022 走看看