以下は、時間のかかる Java Instant 計算方法のサンプル コードです。
import java.time.Duration;
import java.time.Instant;
public class InstantExample {
public static void main(String[] args) {
Instant start = Instant.now();
// 执行需要计算耗时的方法
long result = calculate();
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
long seconds = duration.getSeconds();
long nanos = duration.getNano();
System.out.println("耗时: " + seconds + " 秒 " + nanos + " 纳秒");
System.out.println("计算结果: " + result);
}
private static long calculate() {
long result = 0;
for (long i = 0; i < 1000000000; i++) {
result += i;
}
return result;
}
}
上記のサンプル コードでは、Instant.now() メソッドを使用して現在時刻を取得し、時間のかかるメソッドを実行する前後の現在時刻を取得してから、Duration.between() メソッドを使用して時間を計算しています。 2 つの時点の差を計算し、結果をコンソールに出力します。
サンプルコードでは、単純な計算メソッド calculate() を使用して、時間のかかる計算メソッドをシミュレートしています. このメソッドは、単純な累積演算を実行し、計算結果を返します.
サンプルコードを実行すると、コンソールに時間と計算結果が出力されます。
Instant の計算方法の消費時間と System.currentTimeMillis() の計算時間の消費量の違いと、Instant の方が優れている理由
Instant
System.currentTimeMillis()
どちらもメソッドの時間のかかる計算に使用できますが、Instant
より正確です。
System.currentTimeMillis()
このメソッドは、1970 年 1 月 1 日 UTC から経過したミリ秒数を返します。これを使用して、コード片の実行時間を計算できます。ただし、System.currentTimeMillis()
この方法には特定の精度の問題があります。システム時刻がジャンプしたり、時計がずれたりすると、計算された時刻が不正確になる場合があります。
対照的に、Instant
マシン時間に基づくタイムゾーンのない時計は、より正確で信頼性があります。時間間隔を計算する場合に使用する方が適切ですInstant
。
計算方法に時間がかかる必要がある場合Instant
、特に高い時間精度が必要なシナリオで使用することをお勧めします。