在Java中,可以使用以下方法来测量Java中的经过时间。
1. System.nanoTime()
建议使用此解决方案来测量Java中的经过时间。
ExecutionTime1.java
package com.mkyong.time;
import java.util.concurrent.TimeUnit;
public class ExecutionTime1 {
public static void main(String[] args) throws InterruptedException {
//start
long lStartTime = System.nanoTime();
//task
calculation();
//end
long lEndTime = System.nanoTime();
//time elapsed
long output = lEndTime - lStartTime;
System.out.println("Elapsed time in milliseconds: " + output / 1000000);
}
private static void calculation() throws InterruptedException {
//Sleep 2 seconds
TimeUnit.SECONDS.sleep(2);
}
}
输出可能会有所不同。
2004
2. System.currentTimeMillis()
ExecutionTime2.java
package com.mkyong.time;
import java.util.concurrent.TimeUnit;
public class ExecutionTime2 {
public static void main(String[] args) throws InterruptedException {
long lStartTime = System.currentTimeMillis();
calculation();
long lEndTime = System.currentTimeMillis();
long output = lEndTime - lStartTime;
System.out.println("Elapsed time in milliseconds: " + output);
}
private static void calculation() throws InterruptedException {
//Sleep 2 seconds
TimeUnit.SECONDS.sleep(2);
}
}
输出可能会有所不同。
2006
3. Instant.now()。toEpochMilli()
在Java 8中,您可以尝试新的java.time.Instant
ExecutionTime3.java
package com.mkyong.time;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
public class ExecutionTime3 {
public static void main(String[] args) throws InterruptedException {
long lStartTime = Instant.now().toEpochMilli();
calculation();
long lEndTime = Instant.now().toEpochMilli();
long output = lEndTime - lStartTime;
System.out.println("Elapsed time in milliseconds: " + output);
}
private static void calculation() throws InterruptedException {
//Sleep 2 seconds
TimeUnit.SECONDS.sleep(2);
}
}
输出可能会有所不同。
2006
4. Date()。getTime()
ExecutionTime4.java
package com.mkyong.time;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class ExecutionTime4 {
public static void main(String[] args) throws InterruptedException {
long lStartTime = new Date().getTime();
calculation();
long lEndTime = new Date().getTime();
long output = lEndTime - lStartTime;
System.out.println("Elapsed time in milliseconds: " + output);
}
private static void calculation() throws InterruptedException {
//Sleep 2 seconds
TimeUnit.SECONDS.sleep(2);
}
}
输出可能会有所不同。
2007
参考文献
- Stackoverflow – System.nanoTime()完全没用吗?
- Stackoverflow – System.currentTimeMillis与System.nanoTime
- 系统#nanoTime JavaDoc
- Instant#toEpochMilli JavaDoc
翻译自: https://mkyong.com/java/how-do-calculate-elapsed-execute-time-in-java/