Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

System.nanoTime — measuring elapsed time

System.nanoTime() returns a long reading in nanoseconds. Subtract readings to measure elapsed time, not a date.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public static long nanoTime()
long start = System.nanoTime();
long elapsedNanos = System.nanoTime() - start;

System.nanoTime() measures elapsed time. Calculate System.nanoTime() - start using readings from the same JVM. The origin is arbitrary; readings can be negative.

Nanosecond precision does not guarantee nanosecond resolution. In contrast, System.currentTimeMillis() concerns time since the Unix epoch.

For a nonnegative timeout, use System.nanoTime() - start >= timeoutNanos, not System.nanoTime() >= start + timeoutNanos: addition risks overflow. Subtraction requires an interval shorter than 2^63 nanoseconds, approximately 292 years.

Examples

public class Main {
    public static void main(String[] args) {
        long start = System.nanoTime();
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        long elapsedNanos = System.nanoTime() - start;
        System.out.println(sum);
    }
}

Result

5050

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources