模块 wjybxx.base

类 StopWatch

java.lang.Object
cn.wjybxx.base.time.StopWatch

@NotThreadSafe public class StopWatch extends Object
停表 -- 用于监测每一步的耗时和总耗时。 示例:

  public void execute() {
      // 创建一个已启动的计时器
      final StopWatch stopWatch = StopWatch.createStarted("execute");

      doSomethingA();
      stopWatch.logStep("step1");

      doSomethingB();
      stopWatch.logStep("step2");

      doSomethingC();
      stopWatch.logStep("step3");

      doSomethingD();
      stopWatch.logStep("step4");

      // 输出日志
      logger.info(stopWatch.getLog());
  }
 
 
作者:
wjybxx date 2023/4/4
  • 构造器详细资料

    • StopWatch

      public StopWatch(String name)
      参数:
      name - 推荐命名格式ClassName:MethodName
  • 方法详细资料

    • create

      public static StopWatch create(String name)
    • createStarted

      public static StopWatch createStarted(String name)
    • isStarted

      public boolean isStarted()
    • isRunning

      public boolean isRunning()
    • isSuspended

      public boolean isSuspended()
    • isStopped

      public boolean isStopped()
    • start

      public StopWatch start()
      开始计时。 重复调用start之前,必须调用reset()
      返回:
      this
    • logStep

      public void logStep(String stepName)
      记录该步骤的耗时
      参数:
      stepName - 该步骤的名称
    • suspend

      public void suspend()
      暂停计时
    • resume

      public void resume()
      恢复计时
    • stop

      public void stop()
      如果希望停止计时,则调用该方法。 停止计时后,elapsed()将获得一个稳定的时间值。
    • reset

      public void reset()
      注意:为了安全起见,请要么在代码的开始重置,要么在finally块中重置。
    • restart

      public void restart()
      reset()start()的快捷方法
    • elapsed

      public Duration elapsed()
      获取开始到现在消耗的总时间
    • elapsed

      public long elapsed(TimeUnit desiredUnit)
    • stepElapsed

      public Duration stepElapsed()
      获取当前步骤已消耗的时间
    • stepElapsed

      public long stepElapsed(TimeUnit desiredUnit)
    • listStepElapsed

      public List<Map.Entry<String,Duration>> listStepElapsed()
      获取当前已有的步骤耗时信息
    • getSortedLog

      public String getSortedLog()
      获取按照时间消耗排序后的log。 注意:可以在不调用stop()的情况下调用该方法。 (获得了一个规律,也失去了一个规律,可能并不如未排序的log看着舒服)
    • getLog

      public String getLog()
      获取最终log。
    • toString

      public String toString()
      格式: StopWatch[name={name}ms][a={a}ms,b={b}ms...] 1. StepWatch为标记,方便检索。 2. {x}表示x的耗时。 3. 前半部分为总耗时,后半部分为各步骤耗时。

      Q: 为什么重写toString? A: 在输出日志的时候,我们可能常常使用占位符,那么延迟构建内容就是必须的,这要求我们实现toString()

      覆盖:
      toString 在类中 Object