Java如何測(cè)量方法執(zhí)行時(shí)間

四種方法

為了知道調(diào)用方法用了多長(zhǎng)時(shí)間,我們需要測(cè)量一下方法的執(zhí)行時(shí)間。廢話少說,直接給出四種方法。

JDK currentTimeMillis

先定義一個(gè)call方法,我們來測(cè)量這個(gè)方法的執(zhí)行時(shí)間:

private static void call() {
  try {
    Thread.sleep(500);
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
}

使用JDK方法:

private static void currentTimeMillis() {
  long start = System.currentTimeMillis();
  call();
  long end = System.currentTimeMillis();
  long elapsed = end - start;
  System.out.println(elapsed);
}

JDK nanoTime

使用JDK方法:

private static void nanoTime() {
  long start = System.nanoTime();
  call();
  long end = System.nanoTime();
  long elapsed = end - start;
  elapsed = elapsed / 1000000;
  System.out.println(elapsed);
}

Java8 Time Instant

使用Java 8的方法:

private static void java8TimeInstant() {
  Instant start = Instant.now();
  call();
  Instant end = Instant.now();
  long elapsed = Duration.between(start, end).toMillis();
  System.out.println(elapsed);
}

commons lang StopWatch

使用commons-lang3庫的方法,先引入庫:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>
private static void stopWatch() {
  StopWatch w = new StopWatch();
  w.start();
  call();
  w.stop();
  System.out.println(w.getTime());
}

結(jié)果

基本一樣,但currentTimeMillis容易有誤差,精確的測(cè)量不建議使用:

currentTimeMillis: 501
nanoTime: 500
java8TimeInstant: 500
stopWatch: 500

代碼

代碼請(qǐng)看GitHub: https://github.com/LarryDpk/pkslow-samples

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容