Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to measure execution time

Short answer

Record System.nanoTime() before and after the code and subtract one from the other:

void main() throws InterruptedException {
    long start = System.nanoTime();
    Thread.sleep(150);
    long elapsedMs = (System.nanoTime() - start) / 1_000_000;
 
    IO.println("Took " + elapsedMs + " ms");
}

Output:

Took 172 ms

The exact number of milliseconds will be slightly different for you.

With a Duration

Duration.ofNanos() turns the difference into a convenient object:

void main() {
    long start = System.nanoTime();
    long sum = 0;
    for (int i = 0; i < 50_000_000; i++) {
        sum += i;
    }
    Duration elapsed = Duration.ofNanos(System.nanoTime() - start);
 
    IO.println(sum);
    IO.println(elapsed.toMillis() + " ms");
}

Output:

1249999975000000
30 ms

A helper method

Wrap the measurement in a method that takes the code as a Runnable:

void timed(String label, Runnable code) {
    long start = System.nanoTime();
    code.run();
    IO.println(label + ": " + (System.nanoTime() - start) / 1_000_000 + " ms");
}
 
void main() {
    timed("sort", () -> {
        var numbers = new Random(1).ints(1_000_000).toArray();
        Arrays.sort(numbers);
    });
}

Output:

sort: 250 ms

Common mistake

Measuring with System.currentTimeMillis() and drawing conclusions from a single run. The system clock can be adjusted, and the first run is slower because of JVM warm-up: code is compiled on the fly while it runs. Use nanoTime() for durations, and the JMH library for serious performance comparisons.

Functions used in this recipe

  • Instant — An exact moment on the UTC timeline — for logs, timestamps and measurements.
  • Duration — An amount of time in seconds and nanoseconds — hours, minutes, seconds.

Thanks for reading!

Donate to the site — we work hard for you.