java.lang.Object
cn.wjybxx.base.time.StopWatch
停表 -- 用于监测每一步的耗时和总耗时。
示例:
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
-
构造器概要
构造器 -
方法概要
修饰符和类型方法说明static StopWatchstatic StopWatchcreateStarted(String name) elapsed()获取开始到现在消耗的总时间longgetLog()获取最终log。获取按照时间消耗排序后的log。booleanbooleanbooleanboolean获取当前已有的步骤耗时信息void记录该步骤的耗时voidreset()注意:为了安全起见,请要么在代码的开始重置,要么在finally块中重置。voidrestart()voidresume()恢复计时start()开始计时。获取当前步骤已消耗的时间longstepElapsed(TimeUnit desiredUnit) voidstop()如果希望停止计时,则调用该方法。voidsuspend()暂停计时toString()格式: StopWatch[name={name}ms][a={a}ms,b={b}ms...] 1.
-
构造器详细资料
-
StopWatch
- 参数:
name- 推荐命名格式ClassName:MethodName
-
-
方法详细资料
-
create
-
createStarted
-
isStarted
public boolean isStarted() -
isRunning
public boolean isRunning() -
isSuspended
public boolean isSuspended() -
isStopped
public boolean isStopped() -
start
开始计时。 重复调用start之前,必须调用reset()- 返回:
- this
-
logStep
记录该步骤的耗时- 参数:
stepName- 该步骤的名称
-
suspend
public void suspend()暂停计时 -
resume
public void resume()恢复计时 -
stop
public void stop()如果希望停止计时,则调用该方法。 停止计时后,elapsed()将获得一个稳定的时间值。 -
reset
public void reset()注意:为了安全起见,请要么在代码的开始重置,要么在finally块中重置。 -
restart
public void restart() -
elapsed
获取开始到现在消耗的总时间 -
elapsed
-
stepElapsed
获取当前步骤已消耗的时间 -
stepElapsed
-
listStepElapsed
获取当前已有的步骤耗时信息 -
getSortedLog
获取按照时间消耗排序后的log。 注意:可以在不调用stop()的情况下调用该方法。 (获得了一个规律,也失去了一个规律,可能并不如未排序的log看着舒服) -
getLog
获取最终log。 -
toString
格式: StopWatch[name={name}ms][a={a}ms,b={b}ms...] 1. StepWatch为标记,方便检索。 2.{x}表示x的耗时。 3. 前半部分为总耗时,后半部分为各步骤耗时。Q: 为什么重写
toString? A: 在输出日志的时候,我们可能常常使用占位符,那么延迟构建内容就是必须的,这要求我们实现toString()。
-