LarryDpk
发布于 2022-12-20 / 295 阅读
0

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