6種快速統(tǒng)計代碼執(zhí)行時間的方法,真香!
本文轉載自微信公眾號「Java中文社群」,作者磊哥 。轉載本文請聯(lián)系Java中文社群公眾號。
我們在日常開發(fā)中經常需要測試一些代碼的執(zhí)行時間,但又不想使用向 JMH(Java Microbenchmark Harness,Java 微基準測試套件)這么重的測試框架,所以本文就匯總了一些 Java 中比較常用的執(zhí)行時間統(tǒng)計方法,總共包含以下 6 種,如下圖所示:
方法一:System.currentTimeMillis
此方法為 Java 內置的方法,使用 System#currentTimeMillis 來統(tǒng)計執(zhí)行的時間(統(tǒng)計單位:毫秒),示例代碼如下:
- public class TimeIntervalTest {
- public static void main(String[] args) throws InterruptedException {
- // 開始時間
- long stime = System.currentTimeMillis();
- // 執(zhí)行時間(1s)
- Thread.sleep(1000);
- // 結束時間
- long etime = System.currentTimeMillis();
- // 計算執(zhí)行時間
- System.out.printf("執(zhí)行時長:%d 毫秒.", (etime - stime));
- }
- }
以上程序的執(zhí)行結果為:
執(zhí)行時長:1000 毫秒.
方法二:System.nanoTime
此方法為 Java 內置的方法,使用 System#nanoTime 來統(tǒng)計執(zhí)行時間(統(tǒng)計單位:納秒),它的執(zhí)行方法和 System#currentTimeMillis 類似,示例代碼如下:
- public class TimeIntervalTest {
- public static void main(String[] args) throws InterruptedException {
- // 開始時間
- long stime = System.nanoTime();
- // 執(zhí)行時間(1s)
- Thread.sleep(1000);
- // 結束時間
- long etime = System.nanoTime();
- // 計算執(zhí)行時間
- System.out.printf("執(zhí)行時長:%d 納秒.", (etime - stime));
- }
- }
以上程序的執(zhí)行結果為:
執(zhí)行時長:1000769200 納秒.
小貼士:1 毫秒 = 100 萬納秒。
方法三:new Date
此方法也是 Java 的內置方法,在開始執(zhí)行前 new Date() 創(chuàng)建一個當前時間對象,在執(zhí)行結束之后 new Date() 一個當前執(zhí)行時間,然后再統(tǒng)計兩個 Date 的時間間隔,示例代碼如下:
- import java.util.Date;
- public class TimeIntervalTest {
- public static void main(String[] args) throws InterruptedException {
- // 開始時間
- Date sdate = new Date();
- // 執(zhí)行時間(1s)
- Thread.sleep(1000);
- // 結束時間
- Date edate = new Date();
- // 統(tǒng)計執(zhí)行時間(毫秒)
- System.out.printf("執(zhí)行時長:%d 毫秒." , (edate.getTime() - sdate.getTime()));
- }
- }
以上程序的執(zhí)行結果為:
- 執(zhí)行時長:1000 毫秒.
方法四:Spring StopWatch
如果我們使用的是 Spring 或 Spring Boot 項目,可以在項目中直接使用 StopWatch 對象來統(tǒng)計代碼執(zhí)行時間,示例代碼如下:
- StopWatch stopWatch = new StopWatch();
- // 開始時間
- stopWatch.start();
- // 執(zhí)行時間(1s)
- Thread.sleep(1000);
- // 結束時間
- stopWatch.stop();
- // 統(tǒng)計執(zhí)行時間(秒)
- System.out.printf("執(zhí)行時長:%d 秒.%n", stopWatch.getTotalTimeSeconds()); // %n 為換行
- // 統(tǒng)計執(zhí)行時間(毫秒)
- System.out.printf("執(zhí)行時長:%d 毫秒.%n", stopWatch.getTotalTimeMillis());
- // 統(tǒng)計執(zhí)行時間(納秒)
- System.out.printf("執(zhí)行時長:%d 納秒.%n", stopWatch.getTotalTimeNanos());
以上程序的執(zhí)行結果為:
執(zhí)行時長:0.9996313 秒. 執(zhí)行時長:999 毫秒. 執(zhí)行時長:999631300 納秒.
小貼士:Thread#sleep 方法的執(zhí)行時間稍有偏差,在 1s 左右都是正常的。
方法五:commons-lang3 StopWatch
如果我們使用的是普通項目,那我們可以用 Apache commons-lang3 中的StopWatch 對象來實現(xiàn)時間統(tǒng)計,首先先添加 commons-lang3 的依賴:
- <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.10</version>
- </dependency>
然后編寫時間統(tǒng)計代碼:
- import org.apache.commons.lang3.time.StopWatch;
- import java.util.concurrent.TimeUnit;
- public class TimeIntervalTest {
- public static void main(String[] args) throws InterruptedException {
- StopWatch stopWatch = new StopWatch();
- // 開始時間
- stopWatch.start();
- // 執(zhí)行時間(1s)
- Thread.sleep(1000);
- // 結束時間
- stopWatch.stop();
- // 統(tǒng)計執(zhí)行時間(秒)
- System.out.println("執(zhí)行時長:" + stopWatch.getTime(TimeUnit.SECONDS) + " 秒.");
- // 統(tǒng)計執(zhí)行時間(毫秒)
- System.out.println("執(zhí)行時長:" + stopWatch.getTime(TimeUnit.MILLISECONDS) + " 毫秒.");
- // 統(tǒng)計執(zhí)行時間(納秒)
- System.out.println("執(zhí)行時長:" + stopWatch.getTime(TimeUnit.NANOSECONDS) + " 納秒.");
- }
- }
以上程序的執(zhí)行結果為:
執(zhí)行時長:1 秒. 執(zhí)行時長:1000 毫秒.
執(zhí)行時長:1000555100 納秒.
方法六:Guava Stopwatch
除了 Apache 的 commons-lang3 外,還有一個常用的 Java 工具包,那就是 Google 的 Guava,Guava 中也包含了 Stopwatch 統(tǒng)計類。首先先添加 Guava 的依賴:
- <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>29.0-jre</version>
- </dependency>
然后編寫時間統(tǒng)計代碼:
- import com.google.common.base.Stopwatch;
- import java.util.concurrent.TimeUnit;
- public class TimeIntervalTest {
- public static void main(String[] args) throws InterruptedException {
- // 創(chuàng)建并啟動計時器
- Stopwatch stopwatch = Stopwatch.createStarted();
- // 執(zhí)行時間(1s)
- Thread.sleep(1000);
- // 停止計時器
- stopwatch.stop();
- // 執(zhí)行時間(單位:秒)
- System.out.printf("執(zhí)行時長:%d 秒. %n", stopwatch.elapsed().getSeconds()); // %n 為換行
- // 執(zhí)行時間(單位:毫秒)
- System.out.printf("執(zhí)行時長:%d 豪秒.", stopwatch.elapsed(TimeUnit.MILLISECONDS));
- }
- }
以上程序的執(zhí)行結果為:
執(zhí)行時長:1 秒.
執(zhí)行時長:1000 豪秒.
原理分析本文我們從 Spring 和 Google 的 Guava 源碼來分析一下,它們的 StopWatch 對象底層是如何實現(xiàn)的?
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;
- }
- }
- // .... 忽略其他代碼
- }
從上述 start() 和 stop() 的源碼中可以看出,Spring 實現(xiàn)時間統(tǒng)計的本質還是使用了 Java 的內置方法 System.nanoTime() 來實現(xiàn)的。
2.Google Stopwatch 原理分析
Google Stopwatch 實現(xiàn)的核心源碼如下:
- public final class Stopwatch {
- private final Ticker ticker;
- private boolean isRunning;
- private long elapsedNanos;
- private long startTick;
- @CanIgnoreReturnValue
- public Stopwatch start() {
- Preconditions.checkState(!this.isRunning, "This stopwatch is already running.");
- this.isRunning = true;
- this.startTick = this.ticker.read();
- return this;
- }
- @CanIgnoreReturnValue
- public Stopwatch stop() {
- long tick = this.ticker.read();
- Preconditions.checkState(this.isRunning, "This stopwatch is already stopped.");
- this.isRunning = false;
- this.elapsedNanos += tick - this.startTick;
- return this;
- }
- // 忽略其他源碼...
- }
從上述源碼中可以看出 Stopwatch 對象中調用了 ticker 類來實現(xiàn)時間統(tǒng)計的,那接下來我們進入 ticker 類的實現(xiàn)源碼:
- public abstract class Ticker {
- private static final Ticker SYSTEM_TICKER = new Ticker() {
- public long read() {
- return Platform.systemNanoTime();
- }
- };
- protected Ticker() {
- }
- public abstract long read();
- public static Ticker systemTicker() {
- return SYSTEM_TICKER;
- }
- }
- final class Platform {
- private static final Logger logger = Logger.getLogger(Platform.class.getName());
- private static final PatternCompiler patternCompiler = loadPatternCompiler();
- private Platform() {
- }
- static long systemNanoTime() {
- return System.nanoTime();
- }
- // 忽略其他源碼...
- }
從上述源碼可以看出 Google Stopwatch 實現(xiàn)時間統(tǒng)計的本質還是調用了 Java 內置的 System.nanoTime() 來實現(xiàn)的。
結論
對于所有框架的 StopWatch 來說,其底層都是通過調用 Java 內置的 System.nanoTime() 得到兩個時間,開始時間和結束時間,然后再通過結束時間減去開始時間來統(tǒng)計執(zhí)行時間的。
總結
本文介紹了 6 種實現(xiàn)代碼統(tǒng)計的方法,其中 3 種是 Java 內置的方法:
- System.currentTimeMillis()
- System.nanoTime()
- new Date()
還介紹了 3 種常用框架 spring、commons-langs3、guava 的時間統(tǒng)計器 StopWatch。
在沒有用到 spring、commons-langs3、guava 任意一種框架的情況下,推薦使用 System.currentTimeMillis() 或 System.nanoTime() 來實現(xiàn)代碼統(tǒng)計,否則建議直接使用StopWatch 對象來統(tǒng)計執(zhí)行時間。
知識擴展—Stopwatch 讓統(tǒng)計更方便
StopWatch 存在的意義是讓代碼統(tǒng)計更簡單,比如 Guava 中 StopWatch 使用示例如下:
- import com.google.common.base.Stopwatch;
- import java.util.concurrent.TimeUnit;
- public class TimeIntervalTest {
- public static void main(String[] args) throws InterruptedException {
- // 創(chuàng)建并啟動計時器
- Stopwatch stopwatch = Stopwatch.createStarted();
- // 執(zhí)行時間(1s)
- Thread.sleep(1000);
- // 停止計時器
- stopwatch.stop();
- // 執(zhí)行統(tǒng)計
- System.out.printf("執(zhí)行時長:%d 毫秒. %n",
- stopwatch.elapsed(TimeUnit.MILLISECONDS));
- // 清空計時器
- stopwatch.reset();
- // 再次啟動統(tǒng)計
- stopwatch.start();
- // 執(zhí)行時間(2s)
- Thread.sleep(2000);
- // 停止計時器
- stopwatch.stop();
- // 執(zhí)行統(tǒng)計
- System.out.printf("執(zhí)行時長:%d 秒. %n",
- stopwatch.elapsed(TimeUnit.MILLISECONDS));
- }
- }
我們可以使用一個 Stopwatch 對象統(tǒng)計多段代碼的執(zhí)行時間,也可以通過指定時間類型直接統(tǒng)計出對應的時間間隔,比如我們可以指定時間的統(tǒng)計單位,如秒、毫秒、納秒等類型。
原文鏈接:https://mp.weixin.qq.com/s/e5UeSfygPUWf49AtD0RgMQ