四种方法
为了知道调用方法用了多长时间,我们需要测量一下方法的执行时间。废话少说,直接给出四种方法。
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
文章介绍了在Java中测量方法运行时长的四种方法,包括使用System.currentTimeMillis()、System.nanoTime()、Java8的Instant类以及ApacheCommonsLang3的StopWatch工具。每种方法通过示例代码展示,并指出currentTimeMillis可能存在的误差问题,其他方法提供了更精确的测量结果。
503

被折叠的 条评论
为什么被折叠?



