一、new Date()
public static void main(String[] args) throws InterruptedException {
Date dateStart = new Date();
sleep();
Date dateEnd = new Date();
System.out.printf("执行时长: %d 毫秒",dateEnd.getTime() - dateStart.getTime());
}
public static void sleep() throws InterruptedException {
Thread.sleep(2000);
}
二、System.currentTimeMillis()
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
sleep();
long end = System.currentTimeMillis();
System.out.printf("执行时长: %d 毫秒",end - start);
}
public static void sleep() throws InterruptedException {
Thread.sleep(2000);
}
结果:
三、System.nanoTime()
new StopWatch() 的 内部方法
public static void main(String[] args) throws InterruptedException {
long start = System.nanoTime();
sleep();
long end = System.nanoTime();
// 1毫秒 = 100纳秒
System.out.printf("执行时长: %d 纳秒",end - start);
System.out.printf("执行时长: %d 毫秒",end/1000000 - start/1000000);
}
public static void sleep() throws InterruptedException {
Thread.sleep(2000);
}
结果:
四、spring util 里面提供的 new StopWatch()
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
sleep();
stopWatch.stop();
System.out.printf("执行时长: %d 毫秒",stopWatch.getTotalTimeMillis());
}
public static void sleep() throws InterruptedException {
Thread.sleep(2000);
}
结果:
五、java8 里面提供的 Instant.now()
public static void main(String[] args) throws InterruptedException {
Instant now = Instant.now();
sleep();
Instant end = Instant.now();
System.out.printf("执行时长: %d 毫秒",end.toEpochMilli() - now.toEpochMilli());
}
public static void sleep() throws InterruptedException {
Thread.sleep(2000);
}
结果: