nanoTime Measures Elapsed Durations

Time code sections by subtracting two System.nanoTime calls: the origin is arbitrary, differences are the only meaningful reading, wall clocks drift.

JavaCli Tooling

Code

snippet
public class ElapsedProbe {

    static long timeConcat(int rounds) {
        long start = System.nanoTime(); // 原点任意:只能相减比较差值
        String acc = "";
        for (int i = 0; i < rounds; i++) {
            acc += i;
        }
        return System.nanoTime() - start;
    }

    static long timeBuilder(int rounds) {
        long start = System.nanoTime();
        var sb = new StringBuilder();
        for (int i = 0; i < rounds; i++) {
            sb.append(i);
        }
        return System.nanoTime() - start;
    }

    public static void main(String[] args) {
        long concatNs = timeConcat(2000);
        long builderNs = timeBuilder(2000);
        System.out.println("concat  : " + concatNs / 1_000_000 + " ms");
        System.out.println("builder : " + builderNs / 1_000_000 + " ms");
        System.out.println("builder wins: " + (builderNs < concatNs));
    }
}

Reading the code

The working surface is the class ElapsedProbe and the functions timeConcat, timeBuilder and main — everything else is wiring.

The cycling part of this snippet is for (int i = 0; i < rounds; i++).

Caveats

  • No outside surface: all behavior originates in the standard library.

Putting it to use

The standout signature: static long timeConcat(int rounds)

Watch for labels — concat :, builder :, builder wins: — when the file runs.

Run the file and main steps through timeConcat and timeBuilder, in that order.

Core lines

return System.nanoTime() - start;

Interactive Tools for This Topic

FAQ

What does nanoTime Measures Elapsed Durations print when run?
No setup needed: run the file and look for labeled lines like `concat :`, `builder :`, `builder wins:` in the output.