<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

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

          共 8958字,需瀏覽 18分鐘

           ·

          2020-08-12 19:54

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

          方法一:System.currentTimeMillis

          此方法為 Java 內(nèi)置的方法,使用 System#currentTimeMillis 來統(tǒng)計(jì)執(zhí)行的時(shí)間(統(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)建一個當(dāng)前時(shí)間對象,在執(zhí)行結(jié)束之后 new Date() 一個當(dāng)前執(zhí)行時(shí)間,然后再統(tǒng)計(jì)兩個 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 對象來統(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?對象來實(shí)現(xiàn)時(shí)間統(tǒng)計(jì),首先先添加 commons-lang3 的依賴:


          <dependency>
          ??<groupId>org.apache.commonsgroupId>
          ??<artifactId>commons-lang3artifactId>
          ??<version>3.10version>
          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 外,還有一個常用的 Java 工具包,那就是 Google 的 Guava,Guava 中也包含了 ?Stopwatch?統(tǒng)計(jì)類。首先先添加 Guava 的依賴:


          <dependency>
          ??<groupId>com.google.guavagroupId>
          ??<artifactId>guavaartifactId>
          ??<version>29.0-jreversion>
          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)建并啟動計(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?對象底層是如何實(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?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?對象中調(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é)論

          對于所有框架的 StopWatch?來說,其底層都是通過調(diào)用 Java 內(nèi)置的 System.nanoTime() 得到兩個時(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 對象來統(tǒng)計(jì)執(zhí)行時(shí)間。

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

          StopWatch?存在的意義是讓代碼統(tǒng)計(jì)更簡單,比如 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)建并啟動計(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();
          ????????//?再次啟動統(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));
          ????}
          }

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

          互動話題

          你還知道哪些統(tǒng)計(jì)代碼執(zhí)行時(shí)間的方法嗎?歡迎評論區(qū)補(bǔ)充留言。

          擼了個多線程斷點(diǎn)續(xù)傳下載器,我從中學(xué)習(xí)到了這些知識


          Redis 6.0 除了多線程,這個功能也賊牛逼!


          嵌套事務(wù)、掛起事務(wù),Spring 事務(wù)機(jī)制有什么奧秘?



          點(diǎn)個在看,贊?支持我吧

          瀏覽 62
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  欧美黑吊大战白妞欧美大片 | 亚洲免费无码 | 国产精品一卡2卡3卡4卡5卡免费网站 | 日韩色欲| 久久免费观看视频 |