Java統(tǒng)計(jì)代碼的執(zhí)行時(shí)間的N種方法
在日常開發(fā)中經(jīng)常需要測(cè)試一些代碼的執(zhí)行時(shí)間,但又不想使用向 JMH(Java Microbenchmark Harness,Java 微基準(zhǔn)測(cè)試套件)這么重的測(cè)試框架,所以本文就匯總了一些 Java 中比較常用的執(zhí)行時(shí)間統(tǒng)計(jì)方法,總共包含以下 6 種,如下圖所示:
方法一:System.currentTimeMillis
此方法為 Java 內(nèi)置的方法,使用 System.currentTimeMillis 來執(zhí)行統(tǒng)計(jì)的時(shí)間(統(tǒng)計(jì)單位:毫秒)(統(tǒng)計(jì)單位:毫秒),示例代碼如下:
public class TimeIntervalTest { public static void main(String[] args) throws InterruptedException { // 開始時(shí)間 long stime = System.currentTimeMillis(); // 執(zhí)行時(shí)間(1s) Thread.sleep(1000); // 結(jié)束時(shí)間 long etime = System.currentTimeMillis(); // 計(jì)算執(zhí)行時(shí)間 System.out.printf("執(zhí)行時(shí)長:%d 毫秒.", (etime - stime)); } }
以上程序的執(zhí)行結(jié)果為:
執(zhí)行時(shí)長:1000 毫秒.
方法二:System.nanoTime
此方法為 Java 內(nèi)置的方法,使用 System.nanoTime 來統(tǒng)計(jì)執(zhí)行時(shí)間(統(tǒng)計(jì)單位:納秒),它的執(zhí)行方法和 System.currentTimeMillis 類似,示例代碼如下:
public class TimeIntervalTest { public static void main(String[] args) throws InterruptedException { // 開始時(shí)間 long stime = System.nanoTime(); // 執(zhí)行時(shí)間(1s) Thread.sleep(1000); // 結(jié)束時(shí)間 long etime = System.nanoTime(); // 計(jì)算執(zhí)行時(shí)間 System.out.printf("執(zhí)行時(shí)長:%d 納秒.", (etime - stime)); } }
以上程序的執(zhí)行結(jié)果為:
執(zhí)行時(shí)長:1000769200 納秒.
小貼士:1 毫秒 = 100 萬納秒。
方法三:new Date
此方法也是 Java 的內(nèi)置方法,在開始執(zhí)行前 new Date()
創(chuàng)建一個(gè)當(dāng)前時(shí)間對(duì)象,在執(zhí)行結(jié)束之后 new Date()
一個(gè)當(dāng)前執(zhí)行時(shí)間,然后再統(tǒng)計(jì)兩個(gè) Date
的時(shí)間間隔,示例代碼如下:
import java.util.Date; public class TimeIntervalTest { public static void main(String[] args) throws InterruptedException { // 開始時(shí)間 Date sdate = new Date(); // 執(zhí)行時(shí)間(1s) Thread.sleep(1000); // 結(jié)束時(shí)間 Date edate = new Date(); // 統(tǒng)計(jì)執(zhí)行時(shí)間(毫秒) System.out.printf("執(zhí)行時(shí)長:%d 毫秒." , (edate.getTime() - sdate.getTime())); } }
以上程序的執(zhí)行結(jié)果為:
執(zhí)行時(shí)長:1000 毫秒.
方法四:Spring StopWatch
如果我們使用的是 Spring 或 Spring Boot 項(xiàng)目,可以在項(xiàng)目中直接使用 StopWatch
對(duì)象來統(tǒng)計(jì)代碼執(zhí)行時(shí)間,示例代碼如下:
StopWatch stopWatch = new StopWatch(); // 開始時(shí)間 stopWatch.start(); // 執(zhí)行時(shí)間(1s) Thread.sleep(1000); // 結(jié)束時(shí)間 stopWatch.stop(); // 統(tǒng)計(jì)執(zhí)行時(shí)間(秒) System.out.printf("執(zhí)行時(shí)長:%d 秒.%n", stopWatch.getTotalTimeSeconds()); // %n 為換行 // 統(tǒng)計(jì)執(zhí)行時(shí)間(毫秒) System.out.printf("執(zhí)行時(shí)長:%d 毫秒.%n", stopWatch.getTotalTimeMillis()); // 統(tǒng)計(jì)執(zhí)行時(shí)間(納秒) System.out.printf("執(zhí)行時(shí)長:%d 納秒.%n", stopWatch.getTotalTimeNanos());
以上程序的執(zhí)行結(jié)果為:
執(zhí)行時(shí)長:0.9996313 秒. 執(zhí)行時(shí)長:999 毫秒. 執(zhí)行時(shí)長:999631300 納秒.
小貼士:Thread#sleep 方法的執(zhí)行時(shí)間稍有偏差,在 1s 左右都是正常的。
方法五:commons-lang3 StopWatch
如果我們使用的是普通項(xiàng)目,那我們可以用 Apache commons-lang3 中的 StopWatch
對(duì)象來實(shí)現(xiàn)時(shí)間統(tǒng)計(jì),首先先添加 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>
然后編寫時(shí)間統(tǒng)計(jì)代碼:
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(); // 開始時(shí)間 stopWatch.start(); // 執(zhí)行時(shí)間(1s) Thread.sleep(1000); // 結(jié)束時(shí)間 stopWatch.stop(); // 統(tǒng)計(jì)執(zhí)行時(shí)間(秒) System.out.println("執(zhí)行時(shí)長:" + stopWatch.getTime(TimeUnit.SECONDS) + " 秒."); // 統(tǒng)計(jì)執(zhí)行時(shí)間(毫秒) System.out.println("執(zhí)行時(shí)長:" + stopWatch.getTime(TimeUnit.MILLISECONDS) + " 毫秒."); // 統(tǒng)計(jì)執(zhí)行時(shí)間(納秒) System.out.println("執(zhí)行時(shí)長:" + stopWatch.getTime(TimeUnit.NANOSECONDS) + " 納秒."); } }
以上程序的執(zhí)行結(jié)果為:
執(zhí)行時(shí)長:1 秒. 執(zhí)行時(shí)長:1000 毫秒.
執(zhí)行時(shí)長:1000555100 納秒.
方法六:Guava Stopwatch
除了 Apache 的 commons-lang3 外,還有一個(gè)常用的 Java 工具包,那就是 Google 的 Guava,Guava 中也包含了 Stopwatch
統(tǒng)計(jì)類。首先先添加 Guava 的依賴:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>29.0-jre</version> </dependency>
然后編寫時(shí)間統(tǒng)計(jì)代碼:
import com.google.common.base.Stopwatch; import java.util.concurrent.TimeUnit; public class TimeIntervalTest { public static void main(String[] args) throws InterruptedException { // 創(chuàng)建并啟動(dòng)計(jì)時(shí)器 Stopwatch stopwatch = Stopwatch.createStarted(); // 執(zhí)行時(shí)間(1s) Thread.sleep(1000); // 停止計(jì)時(shí)器 stopwatch.stop(); // 執(zhí)行時(shí)間(單位:秒) System.out.printf("執(zhí)行時(shí)長:%d 秒. %n", stopwatch.elapsed().getSeconds()); // %n 為換行 // 執(zhí)行時(shí)間(單位:毫秒) System.out.printf("執(zhí)行時(shí)長:%d 豪秒.", stopwatch.elapsed(TimeUnit.MILLISECONDS)); } }
以上程序的執(zhí)行結(jié)果為:
執(zhí)行時(shí)長:1 秒.
執(zhí)行時(shí)長:1000 豪秒.
原理分析
本文我們從 Spring 和 Google 的 Guava 源碼來分析一下,它們的 StopWatch
對(duì)象底層是如何實(shí)現(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 實(shí)現(xiàn)時(shí)間統(tǒng)計(jì)的本質(zhì)還是使用了 Java 的內(nèi)置方法 System.nanoTime()
來實(shí)現(xiàn)的。
2.Google Stopwatch 原理分析
Google Stopwatch
實(shí)現(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
對(duì)象中調(diào)用了 ticker
類來實(shí)現(xiàn)時(shí)間統(tǒng)計(jì)的,那接下來我們進(jìn)入 ticker
類的實(shí)現(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
實(shí)現(xiàn)時(shí)間統(tǒng)計(jì)的本質(zhì)還是調(diào)用了 Java 內(nèi)置的 System.nanoTime()
來實(shí)現(xiàn)的。
結(jié)論
對(duì)于所有框架的 StopWatch
來說,其底層都是通過調(diào)用 Java 內(nèi)置的 System.nanoTime()
得到兩個(gè)時(shí)間,開始時(shí)間和結(jié)束時(shí)間,然后再通過結(jié)束時(shí)間減去開始時(shí)間來統(tǒng)計(jì)執(zhí)行時(shí)間的。
總結(jié)
本文介紹了 6 種實(shí)現(xiàn)代碼統(tǒng)計(jì)的方法,其中 3 種是 Java 內(nèi)置的方法:
- System.currentTimeMillis()
- System.nanoTime()
- new Date()
還介紹了 3 種常用框架 spring、commons-langs3、guava 的時(shí)間統(tǒng)計(jì)器 StopWatch。
在沒有用到 spring、commons-langs3、guava 任意一種框架的情況下,推薦使用 System.currentTimeMillis() 或 System.nanoTime() 來實(shí)現(xiàn)代碼統(tǒng)計(jì),否則建議直接使用 StopWatch 對(duì)象來統(tǒng)計(jì)執(zhí)行時(shí)間。
知識(shí)擴(kuò)展—Stopwatch 讓統(tǒng)計(jì)更方便
StopWatch 存在的意義是讓代碼統(tǒng)計(jì)更簡(jiǎn)單,比如 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)建并啟動(dòng)計(jì)時(shí)器 Stopwatch stopwatch = Stopwatch.createStarted(); // 執(zhí)行時(shí)間(1s) Thread.sleep(1000); // 停止計(jì)時(shí)器 stopwatch.stop(); // 執(zhí)行統(tǒng)計(jì) System.out.printf("執(zhí)行時(shí)長:%d 毫秒. %n", stopwatch.elapsed(TimeUnit.MILLISECONDS)); // 清空計(jì)時(shí)器 stopwatch.reset(); // 再次啟動(dòng)統(tǒng)計(jì) stopwatch.start(); // 執(zhí)行時(shí)間(2s) Thread.sleep(2000); // 停止計(jì)時(shí)器 stopwatch.stop(); // 執(zhí)行統(tǒng)計(jì) System.out.printf("執(zhí)行時(shí)長:%d 秒. %n", stopwatch.elapsed(TimeUnit.MILLISECONDS)); } }
我們可以使用一個(gè) Stopwatch
對(duì)象統(tǒng)計(jì)多段代碼的執(zhí)行時(shí)間,也可以通過指定時(shí)間類型直接統(tǒng)計(jì)出對(duì)應(yīng)的時(shí)間間隔,比如我們可以指定時(shí)間的統(tǒng)計(jì)單位,如秒、毫秒、納秒等類型。
到此這篇關(guān)于Java統(tǒng)計(jì)代碼的執(zhí)行時(shí)間的6種方法的文章就介紹到這了,更多相關(guān)Java統(tǒng)計(jì)代碼的執(zhí)行時(shí)間內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java設(shè)計(jì)模式之原型模式詳細(xì)解讀
這篇文章主要介紹了Java設(shè)計(jì)模式之原型模式詳細(xì)解讀,原型模式屬于創(chuàng)建型設(shè)計(jì)模式,用于創(chuàng)建重復(fù)的對(duì)象,且同時(shí)又保證了性能,該設(shè)計(jì)模式的好處是將對(duì)象的創(chuàng)建與調(diào)用方分離,需要的朋友可以參考下2023-12-12springboot默認(rèn)日志框架選擇源碼解析(推薦)
這篇文章主要介紹了springboot默認(rèn)日志框架選擇源碼解析(推薦),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03springboot @ConfigurationProperties和@PropertySource的區(qū)別
這篇文章主要介紹了springboot @ConfigurationProperties和@PropertySource的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06Maven Spring jar包啟動(dòng)報(bào)錯(cuò)問題解決方案
maven 編譯jar包,放在linux服務(wù)器啟動(dòng)不起來,提示:xxxx-0.0.1-SNAPSHOT.jar中沒有主清單屬性,接下來通過本文給大家分享問題原因及解決方案,感興趣的朋友跟隨小編一起看看吧2023-10-10