工具类:org.springframework.util.StopWatch
作用:记录方法执行耗时,统计每个方法的耗时占比
所在模块:spring-core
方法 | 描述 |
void start(String taskName) |
开始一个新的监测任务,可设置任务名称。记录当前时间和任务名称 |
void stop() |
结束当前监测任务。记录任务执行时间,更新总执行时间和任务数量 |
String getLastTaskName() |
获取最后一次执行的监测任务的任务名称 |
long getLastTaskTimeMillis() |
获取最后一次执行的监测任务的执行时间,单位毫秒 |
long getTotalTimeMillis() |
获取所有监测任务的总执行时间,单位毫秒 |
String prettyPrint() |
以字符串形式输出所有监测任务的执行时间和详细信息 |
demo代码:
import org.springframework.util.StopWatch; import java.util.concurrent.TimeUnit; public class StopWatchDemo { private final static StopWatch watch = new StopWatch("task"); public static void test1() throws InterruptedException { watch.start("test1"); TimeUnit.SECONDS.sleep(1); watch.stop(); System.out.println(watch.getLastTaskName() + " 执行耗时:" + watch.getLastTaskTimeMillis() + " ms"); } public static void test2() throws InterruptedException { watch.start("test2"); TimeUnit.SECONDS.sleep(1); watch.stop(); System.out.println(watch.getLastTaskName() + " 执行耗时:" + watch.getLastTaskTimeMillis() + " ms"); } public static void test3() throws InterruptedException { watch.start("test3"); TimeUnit.SECONDS.sleep(2); watch.stop(); System.out.println(watch.getLastTaskName() + " 执行耗时:" + watch.getLastTaskTimeMillis() + " ms"); } public static void main(String[] args) throws InterruptedException { test1(); test2(); test3(); System.out.println("执行总耗时:" + watch.getTotalTimeMillis() + " ms"); TimeUnit.SECONDS.sleep(1); System.out.println(watch.prettyPrint()); } }
console 打印:
test1 执行耗时:1008 ms test2 执行耗时:1008 ms test3 执行耗时:2015 ms 执行总耗时:4031 ms StopWatch 'task': running time = 4031531600 ns --------------------------------------------- ns % Task name --------------------------------------------- 1008106800 025% test1 1008242600 025% test2 2015182200 050% test3
ref:https://blog.csdn.net/JokerLJG/article/details/129010224
标签:Spring,void,watch,耗时,计时器,ms,StopWatch,执行 From: https://www.cnblogs.com/nihaorz/p/17967233