Java如何测量方法执行时间

四种方法

为了知道调用方法用了多长时间,我们需要测量一下方法的执行时间。废话少说,直接给出四种方法。

JDK currentTimeMillis

先定义一个call方法,我们来测量这个方法的执行时间:

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());
}

结果

基本一样,但currentTimeMillis容易有误差,精确的测量不建议使用:

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

代码

代码请看GitHub: https://github.com/LarryDpk/pkslow-samples

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容