成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

6種快速統(tǒng)計(jì)代碼執(zhí)行時(shí)間的方法,真香!

開發(fā) 前端
我們?cè)谌粘i_發(fā)中經(jīng)常需要測(cè)試一些代碼的執(zhí)行時(shí)間,但又不想使用向 JMH(Java Microbenchmark Harness,Java 微基準(zhǔn)測(cè)試套件)這么重的測(cè)試框架,所以本文就匯總了一些 Java 中比較常用的執(zhí)行時(shí)間統(tǒng)計(jì)方法,總共包含以下 6 種。

[[333530]]

本文轉(zhuǎn)載自微信公眾號(hào)「Java中文社群」,作者磊哥  。轉(zhuǎn)載本文請(qǐng)聯(lián)系Java中文社群公眾號(hào)。 

我們?cè)谌粘i_發(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 來(lái)統(tǒng)計(jì)執(zhí)行的時(shí)間(統(tǒng)計(jì)單位:毫秒),示例代碼如下:

  1. public class TimeIntervalTest { 
  2.     public static void main(String[] args) throws InterruptedException { 
  3.         // 開始時(shí)間 
  4.         long stime = System.currentTimeMillis(); 
  5.         // 執(zhí)行時(shí)間(1s) 
  6.         Thread.sleep(1000); 
  7.         // 結(jié)束時(shí)間 
  8.         long etime = System.currentTimeMillis(); 
  9.         // 計(jì)算執(zhí)行時(shí)間 
  10.         System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 毫秒.", (etime - stime)); 
  11.     } 

以上程序的執(zhí)行結(jié)果為:

執(zhí)行時(shí)長(zhǎng):1000 毫秒.

方法二:System.nanoTime

此方法為 Java 內(nèi)置的方法,使用 System#nanoTime 來(lái)統(tǒng)計(jì)執(zhí)行時(shí)間(統(tǒng)計(jì)單位:納秒),它的執(zhí)行方法和 System#currentTimeMillis 類似,示例代碼如下:

  1. public class TimeIntervalTest { 
  2.     public static void main(String[] args) throws InterruptedException { 
  3.         // 開始時(shí)間 
  4.         long stime = System.nanoTime(); 
  5.         // 執(zhí)行時(shí)間(1s) 
  6.         Thread.sleep(1000); 
  7.         // 結(jié)束時(shí)間 
  8.         long etime = System.nanoTime(); 
  9.         // 計(jì)算執(zhí)行時(shí)間 
  10.         System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 納秒.", (etime - stime)); 
  11.     } 

以上程序的執(zhí)行結(jié)果為:

執(zhí)行時(shí)長(zhǎng):1000769200 納秒.

小貼士:1 毫秒 = 100 萬(wàn)納秒。

方法三: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í)間間隔,示例代碼如下:

  1. import java.util.Date
  2.  
  3. public class TimeIntervalTest { 
  4.     public static void main(String[] args) throws InterruptedException { 
  5.         // 開始時(shí)間 
  6.         Date sdate = new Date(); 
  7.         // 執(zhí)行時(shí)間(1s) 
  8.         Thread.sleep(1000); 
  9.         // 結(jié)束時(shí)間 
  10.         Date edate = new Date(); 
  11.         //  統(tǒng)計(jì)執(zhí)行時(shí)間(毫秒) 
  12.         System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 毫秒." , (edate.getTime() - sdate.getTime()));  
  13.     } 

以上程序的執(zhí)行結(jié)果為:

  • 執(zhí)行時(shí)長(zhǎng):1000 毫秒.

方法四:Spring StopWatch

如果我們使用的是 Spring 或 Spring Boot 項(xiàng)目,可以在項(xiàng)目中直接使用 StopWatch 對(duì)象來(lái)統(tǒng)計(jì)代碼執(zhí)行時(shí)間,示例代碼如下:

  1. StopWatch stopWatch = new StopWatch(); 
  2. // 開始時(shí)間 
  3. stopWatch.start(); 
  4. // 執(zhí)行時(shí)間(1s) 
  5. Thread.sleep(1000); 
  6. // 結(jié)束時(shí)間 
  7. stopWatch.stop(); 
  8. // 統(tǒng)計(jì)執(zhí)行時(shí)間(秒) 
  9. System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 秒.%n", stopWatch.getTotalTimeSeconds()); // %n 為換行 
  10. // 統(tǒng)計(jì)執(zhí)行時(shí)間(毫秒) 
  11. System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 毫秒.%n", stopWatch.getTotalTimeMillis());  
  12. // 統(tǒng)計(jì)執(zhí)行時(shí)間(納秒) 
  13. System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 納秒.%n", stopWatch.getTotalTimeNanos()); 

以上程序的執(zhí)行結(jié)果為:

執(zhí)行時(shí)長(zhǎng):0.9996313 秒. 執(zhí)行時(shí)長(zhǎng):999 毫秒. 執(zhí)行時(shí)長(zhǎng):999631300 納秒.

小貼士:Thread#sleep 方法的執(zhí)行時(shí)間稍有偏差,在 1s 左右都是正常的。

方法五:commons-lang3 StopWatch

如果我們使用的是普通項(xiàng)目,那我們可以用 Apache commons-lang3 中的StopWatch 對(duì)象來(lái)實(shí)現(xiàn)時(shí)間統(tǒng)計(jì),首先先添加 commons-lang3 的依賴:

  1. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> 
  2. <dependency> 
  3.   <groupId>org.apache.commons</groupId> 
  4.   <artifactId>commons-lang3</artifactId> 
  5.   <version>3.10</version> 
  6. </dependency> 

然后編寫時(shí)間統(tǒng)計(jì)代碼:

  1. import org.apache.commons.lang3.time.StopWatch; 
  2.  
  3. import java.util.concurrent.TimeUnit; 
  4.  
  5. public class TimeIntervalTest { 
  6.     public static void main(String[] args) throws InterruptedException { 
  7.         StopWatch stopWatch = new StopWatch(); 
  8.         // 開始時(shí)間 
  9.         stopWatch.start(); 
  10.         // 執(zhí)行時(shí)間(1s) 
  11.         Thread.sleep(1000); 
  12.         // 結(jié)束時(shí)間 
  13.         stopWatch.stop(); 
  14.         // 統(tǒng)計(jì)執(zhí)行時(shí)間(秒) 
  15.         System.out.println("執(zhí)行時(shí)長(zhǎng):" + stopWatch.getTime(TimeUnit.SECONDS) + " 秒."); 
  16.         // 統(tǒng)計(jì)執(zhí)行時(shí)間(毫秒) 
  17.         System.out.println("執(zhí)行時(shí)長(zhǎng):" + stopWatch.getTime(TimeUnit.MILLISECONDS) + " 毫秒."); 
  18.         // 統(tǒng)計(jì)執(zhí)行時(shí)間(納秒) 
  19.         System.out.println("執(zhí)行時(shí)長(zhǎng):" + stopWatch.getTime(TimeUnit.NANOSECONDS) + " 納秒."); 
  20.     } 

以上程序的執(zhí)行結(jié)果為:

執(zhí)行時(shí)長(zhǎng):1 秒. 執(zhí)行時(shí)長(zhǎng):1000 毫秒.

執(zhí)行時(shí)長(zhǎng):1000555100 納秒.

方法六:Guava Stopwatch

除了 Apache 的 commons-lang3 外,還有一個(gè)常用的 Java 工具包,那就是 Google 的 Guava,Guava 中也包含了 Stopwatch 統(tǒng)計(jì)類。首先先添加 Guava 的依賴:

  1. <!-- https://mvnrepository.com/artifact/com.google.guava/guava --> 
  2. <dependency> 
  3.   <groupId>com.google.guava</groupId> 
  4.   <artifactId>guava</artifactId> 
  5.   <version>29.0-jre</version> 
  6. </dependency> 

然后編寫時(shí)間統(tǒng)計(jì)代碼:

  1. import com.google.common.base.Stopwatch; 
  2.  
  3. import java.util.concurrent.TimeUnit; 
  4.  
  5. public class TimeIntervalTest { 
  6.     public static void main(String[] args) throws InterruptedException { 
  7.         // 創(chuàng)建并啟動(dòng)計(jì)時(shí)器 
  8.         Stopwatch stopwatch = Stopwatch.createStarted(); 
  9.         // 執(zhí)行時(shí)間(1s) 
  10.         Thread.sleep(1000); 
  11.         // 停止計(jì)時(shí)器 
  12.         stopwatch.stop(); 
  13.         // 執(zhí)行時(shí)間(單位:秒) 
  14.         System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 秒. %n", stopwatch.elapsed().getSeconds()); // %n 為換行 
  15.         // 執(zhí)行時(shí)間(單位:毫秒) 
  16.         System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 豪秒.", stopwatch.elapsed(TimeUnit.MILLISECONDS)); 
  17.     } 

以上程序的執(zhí)行結(jié)果為:

執(zhí)行時(shí)長(zhǎng):1 秒.

執(zhí)行時(shí)長(zhǎng):1000 豪秒.

原理分析本文我們從 Spring 和 Google 的 Guava 源碼來(lái)分析一下,它們的 StopWatch 對(duì)象底層是如何實(shí)現(xiàn)的?

1.Spring StopWatch 原理分析

在 Spring 中 StopWatch 的核心源碼如下:

  1. package org.springframework.util; 
  2.  
  3. import java.text.NumberFormat; 
  4. import java.util.LinkedList; 
  5. import java.util.List; 
  6. import java.util.concurrent.TimeUnit; 
  7. import org.springframework.lang.Nullable; 
  8.  
  9. public class StopWatch { 
  10.     private final String id; 
  11.     private boolean keepTaskList; 
  12.     private final List<StopWatch.TaskInfo> taskList; 
  13.     private long startTimeNanos; 
  14.     @Nullable 
  15.     private String currentTaskName; 
  16.     @Nullable 
  17.     private StopWatch.TaskInfo lastTaskInfo; 
  18.     private int taskCount; 
  19.     private long totalTimeNanos; 
  20.  
  21.     public StopWatch() { 
  22.         this(""); 
  23.     } 
  24.  
  25.     public StopWatch(String id) { 
  26.         this.keepTaskList = true
  27.         this.taskList = new LinkedList(); 
  28.         this.id = id; 
  29.     } 
  30.  
  31.     public String getId() { 
  32.         return this.id; 
  33.     } 
  34.  
  35.     public void setKeepTaskList(boolean keepTaskList) { 
  36.         this.keepTaskList = keepTaskList; 
  37.     } 
  38.  
  39.     public void start() throws IllegalStateException { 
  40.         this.start(""); 
  41.     } 
  42.  
  43.     public void start(String taskName) throws IllegalStateException { 
  44.         if (this.currentTaskName != null) { 
  45.             throw new IllegalStateException("Can't start StopWatch: it's already running"); 
  46.         } else { 
  47.             this.currentTaskName = taskName; 
  48.             this.startTimeNanos = System.nanoTime(); 
  49.         } 
  50.     } 
  51.  
  52.     public void stop() throws IllegalStateException { 
  53.         if (this.currentTaskName == null) { 
  54.             throw new IllegalStateException("Can't stop StopWatch: it's not running"); 
  55.         } else { 
  56.             long lastTime = System.nanoTime() - this.startTimeNanos; 
  57.             this.totalTimeNanos += lastTime; 
  58.             this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime); 
  59.             if (this.keepTaskList) { 
  60.                 this.taskList.add(this.lastTaskInfo); 
  61.             } 
  62.  
  63.             ++this.taskCount; 
  64.             this.currentTaskName = null
  65.         } 
  66.     } 
  67.     // .... 忽略其他代碼 

從上述 start() 和 stop() 的源碼中可以看出,Spring 實(shí)現(xiàn)時(shí)間統(tǒng)計(jì)的本質(zhì)還是使用了 Java 的內(nèi)置方法 System.nanoTime() 來(lái)實(shí)現(xiàn)的。

2.Google Stopwatch 原理分析

Google Stopwatch 實(shí)現(xiàn)的核心源碼如下:

  1. public final class Stopwatch { 
  2.     private final Ticker ticker; 
  3.     private boolean isRunning; 
  4.     private long elapsedNanos; 
  5.     private long startTick; 
  6.     @CanIgnoreReturnValue 
  7.     public Stopwatch start() { 
  8.         Preconditions.checkState(!this.isRunning, "This stopwatch is already running."); 
  9.         this.isRunning = true
  10.         this.startTick = this.ticker.read(); 
  11.         return this; 
  12.     } 
  13.  
  14.     @CanIgnoreReturnValue 
  15.     public Stopwatch stop() { 
  16.         long tick = this.ticker.read(); 
  17.         Preconditions.checkState(this.isRunning, "This stopwatch is already stopped."); 
  18.         this.isRunning = false
  19.         this.elapsedNanos += tick - this.startTick; 
  20.         return this; 
  21.     } 
  22.     // 忽略其他源碼... 

從上述源碼中可以看出 Stopwatch 對(duì)象中調(diào)用了 ticker 類來(lái)實(shí)現(xiàn)時(shí)間統(tǒng)計(jì)的,那接下來(lái)我們進(jìn)入 ticker 類的實(shí)現(xiàn)源碼:

  1. public abstract class Ticker { 
  2.     private static final Ticker SYSTEM_TICKER = new Ticker() { 
  3.         public long read() { 
  4.             return Platform.systemNanoTime(); 
  5.         } 
  6.     }; 
  7.     protected Ticker() { 
  8.     } 
  9.     public abstract long read(); 
  10.     public static Ticker systemTicker() { 
  11.         return SYSTEM_TICKER; 
  12.     } 
  13. final class Platform { 
  14.     private static final Logger logger = Logger.getLogger(Platform.class.getName()); 
  15.     private static final PatternCompiler patternCompiler = loadPatternCompiler(); 
  16.  
  17.     private Platform() { 
  18.     } 
  19.  
  20.     static long systemNanoTime() { 
  21.         return System.nanoTime(); 
  22.     } 
  23.     // 忽略其他源碼... 

從上述源碼可以看出 Google Stopwatch 實(shí)現(xiàn)時(shí)間統(tǒng)計(jì)的本質(zhì)還是調(diào)用了 Java 內(nèi)置的 System.nanoTime() 來(lái)實(shí)現(xiàn)的。

結(jié)論

對(duì)于所有框架的 StopWatch 來(lái)說(shuō),其底層都是通過(guò)調(diào)用 Java 內(nèi)置的 System.nanoTime() 得到兩個(gè)時(shí)間,開始時(shí)間和結(jié)束時(shí)間,然后再通過(guò)結(jié)束時(shí)間減去開始時(shí)間來(lái)統(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。

在沒(méi)有用到 spring、commons-langs3、guava 任意一種框架的情況下,推薦使用 System.currentTimeMillis() 或 System.nanoTime() 來(lái)實(shí)現(xiàn)代碼統(tǒng)計(jì),否則建議直接使用StopWatch 對(duì)象來(lái)統(tǒng)計(jì)執(zhí)行時(shí)間。

知識(shí)擴(kuò)展—Stopwatch 讓統(tǒng)計(jì)更方便

StopWatch 存在的意義是讓代碼統(tǒng)計(jì)更簡(jiǎn)單,比如 Guava 中 StopWatch 使用示例如下:

  1. import com.google.common.base.Stopwatch; 
  2.  
  3. import java.util.concurrent.TimeUnit; 
  4.  
  5. public class TimeIntervalTest { 
  6.     public static void main(String[] args) throws InterruptedException { 
  7.         // 創(chuàng)建并啟動(dòng)計(jì)時(shí)器 
  8.         Stopwatch stopwatch = Stopwatch.createStarted(); 
  9.         // 執(zhí)行時(shí)間(1s) 
  10.         Thread.sleep(1000); 
  11.         // 停止計(jì)時(shí)器 
  12.         stopwatch.stop(); 
  13.         // 執(zhí)行統(tǒng)計(jì) 
  14.         System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 毫秒. %n"
  15.                 stopwatch.elapsed(TimeUnit.MILLISECONDS)); 
  16.         // 清空計(jì)時(shí)器 
  17.         stopwatch.reset(); 
  18.         // 再次啟動(dòng)統(tǒng)計(jì) 
  19.         stopwatch.start(); 
  20.         // 執(zhí)行時(shí)間(2s) 
  21.         Thread.sleep(2000); 
  22.         // 停止計(jì)時(shí)器 
  23.         stopwatch.stop(); 
  24.         // 執(zhí)行統(tǒng)計(jì) 
  25.         System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 秒. %n"
  26.                 stopwatch.elapsed(TimeUnit.MILLISECONDS)); 
  27.     } 

我們可以使用一個(gè) Stopwatch 對(duì)象統(tǒng)計(jì)多段代碼的執(zhí)行時(shí)間,也可以通過(guò)指定時(shí)間類型直接統(tǒng)計(jì)出對(duì)應(yīng)的時(shí)間間隔,比如我們可以指定時(shí)間的統(tǒng)計(jì)單位,如秒、毫秒、納秒等類型。

原文鏈接:https://mp.weixin.qq.com/s/e5UeSfygPUWf49AtD0RgMQ

 

責(zé)任編輯:武曉燕 來(lái)源: Java中文社群
相關(guān)推薦

2018-07-18 15:13:56

MCU代碼時(shí)間

2010-09-08 15:00:03

SQL語(yǔ)句執(zhí)行

2012-01-10 10:44:36

字符串

2010-11-18 15:53:30

Oracle語(yǔ)句執(zhí)行時(shí)

2021-02-24 11:44:35

語(yǔ)言計(jì)算函數(shù)嵌入式系統(tǒng)

2009-11-26 11:05:44

PHP計(jì)算頁(yè)面執(zhí)行時(shí)間

2024-05-10 08:44:53

C#軟件開發(fā)優(yōu)化代碼

2011-05-17 13:32:04

oracle

2025-01-16 07:00:00

AOPSpringBoot后端

2023-01-27 15:28:04

開發(fā)Python內(nèi)存

2010-09-06 13:17:19

SQL Server語(yǔ)句

2010-04-28 12:33:36

Oracle自定義函數(shù)

2024-04-12 07:50:40

Python監(jiān)控利器Time 模塊

2024-07-03 13:51:02

SQL毛刺數(shù)據(jù)庫(kù)

2019-08-28 07:45:45

數(shù)據(jù)存儲(chǔ)層多線程

2020-08-03 16:00:31

Linux命令進(jìn)程

2018-11-22 09:15:45

Linux命令進(jìn)程

2024-05-07 08:55:46

C#軟件開發(fā)代碼執(zhí)行時(shí)間

2021-11-05 07:47:55

API計(jì)算任務(wù)

2020-12-25 08:52:53

SQLMysql 數(shù)據(jù)庫(kù)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 国产精品高潮呻吟久久 | 国产成人99久久亚洲综合精品 | 91精品国产91久久久久久吃药 | 天天干天天操天天射 | 欧美片网站免费 | 四虎影院一区二区 | 国产精品一区三区 | 精品一区二区三区在线观看 | 黄色一级特级片 | 久久精品影视 | 日韩视频在线观看一区二区 | 日本三级全黄三级a | 看一级黄色毛片 | 亚洲免费一区 | 欧美视频在线看 | 精品国产乱码久久久久久闺蜜 | 久久99久久99精品免视看婷婷 | 日本天堂一区二区 | 欧美激情视频一区二区三区免费 | 99免费精品视频 | 在线观看免费av网 | 天天插天天干 | av毛片 | 日韩中文一区 | 91免费版在线观看 | 一区二区三区免费 | 日韩精品在线播放 | 老司机免费视频 | 亚洲精品一区二区二区 | 亚洲成人网在线 | 日韩国产中文字幕 | 亚洲精品日韩在线 | 美女视频黄的免费 | av国产精品| 久久新 | 欧美日韩成人在线观看 | 久久精品欧美一区二区三区麻豆 | 国产精品综合色区在线观看 | 国产在线网站 | 久久久精品在线 | 国产 亚洲 网红 主播 |