Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

System.nanoTime()

Returns a high-resolution timer value in nanoseconds — for measuring durations. See also currentTimeMillis().

Available since: Java 5

Syntax

public static long nanoTime()

Return value

longNanoseconds since an arbitrary origin; only the difference between two values is meaningful.

Examples

Timing a loop (the time changes from run to run):

void main() {
    long start = System.nanoTime();
    long sum = 0;
    for (int i = 0; i < 10_000_000; i++) {
        sum += i;
    }
    long elapsed = System.nanoTime() - start;
 
    IO.println("sum = " + sum);
    IO.println("took " + elapsed / 1_000_000 + " ms");
}

Output:

sum = 49999995000000
took 11 ms

System.currentTimeMillis() is the current time in milliseconds since January 1, 1970 (UTC):

void main() {
    long now = System.currentTimeMillis();
    IO.println(now);
    IO.println(Instant.ofEpochMilli(now));
}

Output:

1791099664011
2026-10-04T07:41:04.011Z

Notes

nanoTime() is not tied to the calendar: its origin is arbitrary, but it never goes backwards. So durations are measured with nanoTime(), while a point in time comes from currentTimeMillis() or Instant.now() — the system clock can be adjusted, and the difference of two currentTimeMillis() values may be wrong. A difference is easy to turn into Duration.ofNanos(elapsed). For serious performance measurements use the JMH library: the first run of code is always slower because the JVM warms up.

See also

  • Duration — An amount of time in seconds and nanoseconds — hours, minutes, seconds.
  • Instant — An exact moment on the UTC timeline — for logs, timestamps and measurements.
  • Runtime.getRuntime() — Returns the Runtime object of the current JVM: memory, processor count, shutdown hooks.

Related recipes

In the tutorial

  • Dates and times — The java.time package — LocalDate, LocalTime, LocalDateTime, date arithmetic, Period, Duration, ChronoUnit, time zones and Instant.

Thanks for reading!

Donate to the site — we work hard for you.