学习使用 Java 8 发布前后的各种技术计算执行时间或测量经过的时间程序或一些 Java 语句。
如果我们使用 Java 8 – 我们可以尝试新的 java.time.Instant 和 java.time.Duration 类。在 Java 8 以下,继续本文中的下一个方法。
要获取不同时间单位的运行执行时间,请使用以下方法。它测量两个 Instant 之间的持续时间。 Instant 表示自纪元以来经过的时间。
long timeElapsed = Duration.between(startInstant, finishInstant).toMillis();
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
public class Main
{
public static void main(String[] args) throws ParseException
{
Instant start = Instant.now();
//Measure execution time for this method
methodToTime();
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis(); //in millis
}
private static void methodToTime() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
程序输出。
3000
这是在 Java 中测量经过时间的最推荐的解决方案。它提供两次测量之间经过的时间的纳秒级精度。这是在 Java 中计算线程执行时间 的首选方法。
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
public class Main
{
public static void main(String[] args) throws ParseException
{
long startTime = System.nanoTime();
methodToTime(); //Measure execution time for this method
long endTime = System.nanoTime();
long durationInNano = (endTime - startTime); //Total execution time in nano seconds
//Same duration in millis
long durationInMillis = TimeUnit.NANOSECONDS.toMillis(durationInNano); //Total execution time in nano seconds
System.out.println(durationInNano);
System.out.println(durationInMillis);
}
private static void methodToTime() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
程序输出。
3000076434 //More precise
3000
如果您不太关心纳米级精度,或者不幸的是仍然停留在旧的 Java 版本中——您应该使用 System.currentTimeMillis()
方法。
import java.text.ParseException;
import java.util.concurrent.TimeUnit;
public class Main
{
public static void main(String[] args) throws ParseException
{
long startTime = System.currentTimeMillis();
methodToTime(); //Measure execution time for this method
long endTime = System.currentTimeMillis();
long duration = (endTime - startTime); //Total execution time in milli seconds
System.out.println(duration);
}
private static void methodToTime() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
程序输出。
3000
我们可以将上述以毫秒为单位的时间换算成小时、分钟、秒等其他时间单位,以相应的时间单位衡量执行时间。
快乐学习!!
标签2: Java Date Time地址:https://www.cundage.com/article/execution-elapsed-time.html