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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.