6种快速统计代码执行时间的方法,真香!(5)
2023-05-02 来源:飞速影视
毫秒) System.out.printf("执行时长:%d 豪秒.", stopwatch.elapsed(TimeUnit.MILLISECONDS)); } }
以上程序的执行结果为:
执行时长:1 秒.
执行时长:1000 毫秒.
原理分析本文我们从 Spring 和 Google 的 Guava 源码来分析一下,它们的 StopWatch 对象底层是如何实现的?
1.Spring StopWatch 原理分析
在 Spring 中 StopWatch 的核心源码如下:
package org.springframework.util; import java.text.NumberFormat; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import org.springframework.lang.Nullable; public class StopWatch { private final String id; private boolean keepTaskList; private final List<StopWatch.TaskInfo> taskList; private long startTimeNanos; @Nullable private String currentTaskName; @Nullable private StopWatch.TaskInfo lastTaskInfo; private int taskCount; private long totalTimeNanos; public StopWatch() { this(""); } public StopWatch(String id) { this.keepTaskList = true; this.taskList = new LinkedList(); this.id = id; } public String getId() { return this.id; } public void setKeepTaskList(boolean keepTaskList) { this.keepTaskList = keepTaskList; } public void start() throws IllegalStateException { this.start(""); } public void start(String taskName) throws IllegalStateException { if (this.currentTaskName != null) { throw new IllegalStateException("Can"t start StopWatch: it"s already running"); } else { this.currentTaskName = taskName; this.startTimeNanos = System.nanoTime(); } } public void stop() throws IllegalStateException { if (this.currentTaskName == null) { throw new IllegalStateException("Can"t stop StopWatch: it"s not running"); } else { long lastTime = System.nanoTime() - this.startTimeNanos; this.totalTimeNanos = lastTime; this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime); if (this.keepTaskList) { this.taskList.add(this.lastTaskInfo); } this.taskCount; this.currentTaskName = null; } } // .... 忽略其他代码 }
本站仅为学习交流之用,所有视频和图片均来自互联网收集而来,版权归原创者所有,本网站只提供web页面服务,并不提供资源存储,也不参与录制、上传
若本站收录的节目无意侵犯了贵司版权,请发邮件(我们会在3个工作日内删除侵权内容,谢谢。)
www.fs94.org-飞速影视 粤ICP备74369512号