<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í)間的方法,你知道幾個(gè)?

          共 8915字,需瀏覽 18分鐘

           ·

          2020-08-01 03:32




          我們?cè)谌粘i_(kā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ì)單位:毫秒),示例代碼如下:

          public?class?TimeIntervalTest?{
          ????public?static?void?main(String[]?args)?throws?InterruptedException?{
          ????????//?開(kāi)始時(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í)長(zhǎng):%d 毫秒.",?(etime?-?stime));
          ????}
          }

          以上程序的執(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 類似,示例代碼如下:

          public?class?TimeIntervalTest?{
          ????public?static?void?main(String[]?args)?throws?InterruptedException?{
          ????????//?開(kāi)始時(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í)長(zhǎng):%d 納秒.",?(etime?-?stime));
          ????}
          }

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

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

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

          方法三:new Date

          此方法也是 Java 的內(nèi)置方法,在開(kā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?{
          ????????//?開(kāi)始時(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í)長(zhǎng):%d 毫秒."?,?(edate.getTime()?-?sdate.getTime()));?
          ????}
          }

          以上程序的執(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í)間,示例代碼如下:

          StopWatch?stopWatch?=?new?StopWatch();
          //?開(kāi)始時(shí)間
          stopWatch.start();
          //?執(zhí)行時(shí)間(1s)
          Thread.sleep(1000);
          //?結(jié)束時(shí)間
          stopWatch.stop();
          //?統(tǒng)計(jì)執(zhí)行時(shí)間(秒)
          System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 秒.%n",?stopWatch.getTotalTimeSeconds());?//?%n?為換行
          //?統(tǒng)計(jì)執(zhí)行時(shí)間(毫秒)
          System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 毫秒.%n",?stopWatch.getTotalTimeMillis());?
          //?統(tǒng)計(jì)執(zhí)行時(shí)間(納秒)
          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 的依賴:


          <dependency>
          ??<groupId>org.apache.commonsgroupId>
          ??<artifactId>commons-lang3artifactId>
          ??<version>3.10version>
          dependency>

          然后編寫(xiě)時(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();
          ????????//?開(kāi)始時(shí)間
          ????????stopWatch.start();
          ????????//?執(zhí)行時(shí)間(1s)
          ????????Thread.sleep(1000);
          ????????//?結(jié)束時(shí)間
          ????????stopWatch.stop();
          ????????//?統(tǒng)計(jì)執(zhí)行時(shí)間(秒)
          ????????System.out.println("執(zhí)行時(shí)長(zhǎng):"?+?stopWatch.getTime(TimeUnit.SECONDS)?+?"?秒.");
          ????????//?統(tǒng)計(jì)執(zhí)行時(shí)間(毫秒)
          ????????System.out.println("執(zhí)行時(shí)長(zhǎng):"?+?stopWatch.getTime(TimeUnit.MILLISECONDS)?+?"?毫秒.");
          ????????//?統(tǒng)計(jì)執(zhí)行時(shí)間(納秒)
          ????????System.out.println("執(zhí)行時(shí)長(zhǎng):"?+?stopWatch.getTime(TimeUnit.NANOSECONDS)?+?"?納秒.");
          ????}
          }

          以上程序的執(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 的依賴:


          <dependency>
          ??<groupId>com.google.guavagroupId>
          ??<artifactId>guavaartifactId>
          ??<version>29.0-jreversion>
          dependency>

          然后編寫(xiě)時(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í)長(zhǎng):%d 秒. %n",?stopwatch.elapsed().getSeconds());?//?%n?為換行
          ????????//?執(zhí)行時(shí)間(單位:毫秒)
          ????????System.out.printf("執(zhí)行時(shí)長(zhǎng):%d 豪秒.",?stopwatch.elapsed(TimeUnit.MILLISECONDS));
          ????}
          }

          以上程序的執(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 的核心源碼如下:

          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()?來(lái)實(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 類來(lái)實(shí)現(xiàn)時(shí)間統(tǒng)計(jì)的,那接下來(lái)我們進(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()?來(lái)實(shí)現(xiàn)的。

          結(jié)論

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

          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í)長(zhǎng):%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í)長(zhǎng):%d 秒. %n",
          ????????????????stopwatch.elapsed(TimeUnit.MILLISECONDS));
          ????}
          }

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


          ? ? ? ?
          ???
          性能調(diào)優(yōu)必備利器之 JMH
          教你寫(xiě) Bug,常見(jiàn)的 OOM 異常分析
          為什么 Kafka 能這么快的 6 個(gè)原因

          覺(jué)得不錯(cuò),點(diǎn)個(gè)在看~

          瀏覽 40
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

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

          手機(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>
                  日韩高清无码人妻 | 人人射人人操人人舔 | 黄片免费看 | 女人18毛片水多毛片久久1 | 国产精品久久久久久久久久久久久久久久久 |