nanoTime() 返回的是 正在运行的 Java 虚拟机的高分辨率时间源的当前值,以纳秒为单位。
currentTimeMillis() 返回的是 当前时间与 UTC 1970 年 1 月 1 日午夜之间的差异,以毫秒为单位。
public class Elapsed {
public static void main(String[] args) {
long start, end;
System.out.println("Timing for loop from 0 to 100,000,000");
start = System.currentTimeMillis();
System.out.println("start currentTimeMillis: " + start);
for (long i=0; i<100000000L; i++);
end = System.currentTimeMillis();
System.out.println("end currentTimeMillis: " + end);
System.out.println("Elapsed time: " + (end - start));
System.out.println("Timing for loop from 0 to 100,000,000");
start = System.nanoTime();
System.out.println("nano nanoTime: " + start);
for (long i=0; i<100000000L; i++);
end = System.nanoTime();
System.out.println("end nanoTime: " + end);
System.out.println("Elapsed time: " + (end - start));
}
}
输出结果
Timing for loop from 0 to 100,000,000 start currentTimeMillis: 1653033370155 end currentTimeMillis: 1653033370186 Elapsed time: 31 Timing for loop from 0 to 100,000,000 nano nanoTime: 261630972426900 end nanoTime: 261631001267300 Elapsed time: 28840400 // 这里等于28.84 ms
nanoTime()要比currentTimeMillis() 更加精准,但是currentTimeMillis() 转换成Date



