四種方法
為了知道調(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