最近新学了一个代码计时方法StopWatch替代繁琐的System.currentTimeMillis()计时,常见的工具类有org.springframework.util.StopWatch、org.apache.commons.lang3.time.StopWatch。(前者支持多任务执行时间统计,后者适用单任务计时)
1.org.springframework.util.StopWatch
源码解析:
public class StopWatch { /** * Identifier of this stop watch. * Handy when we have output from multiple stop watches * and need to distinguish between them in log or console output. */ private final String id; private boolean keepTaskList = true; private final List<TaskInfo> taskList = new LinkedList<>(); /** Start time of the current task */ private long startTimeMillis; /** Name of the current task */ @Nullable private String currentTaskName; @Nullable private TaskInfo lastTaskInfo; private int taskCount; /** Total running time */ private long totalTimeMillis;
...
可以看到源码中的 List<TaskInfo> taskList,用于存储一组任务的耗时时间。
比如:
// 定义一个计时器 StopWatch stopWatch = new StopWatch("统一一组任务耗时"); // 任务一耗时 stopWatch.start("任务一"); Thread.sleep(1000); stopWatch.stop(); // 任务二耗时 stopWatch.start("任务二"); Thread.sleep(2000); stopWatch.stop(); // 打印出所有任务耗时 String result = stopWatch.prettyPrint(); System.err.println(result);
执行结果:
StopWatch '统一一组任务耗时': running time (millis) = 3004
-----------------------------------------
ms % Task name
-----------------------------------------
01003 033% 任务一
02001 067% 任务二
2.org.apache.commons.lang3.time.StopWatch
// 统计执行时间 StopWatch duration = new StopWatch(); duration.start(); //任务 Thread.sleep(2000); duration.stop(); System.err.println(duration.getTime(TimeUnit.MILLISECONDS));