JIT warm-up and honest timing tests
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A Java program does not run at full speed from its first line. Its hot code starts in the interpreter and gets faster as the JIT compiles it, so any timing test has to account for that warm-up, and for a few other traps, before its numbers mean anything.
Warm-up: why the first runs are slow
Warm-up is the period after the JVM starts during which hot code is still being interpreted, profiled and compiled. During warm-up the same request or loop can be several times slower than it will be later.
Example 1 · An exam-results server just after a restart
public class ResultsServerDemo { static char grade(int marks) { if (marks >= 90) return 'A'; if (marks >= 75) return 'B'; if (marks >= 60) return 'C'; if (marks >= 40) return 'D'; return 'F'; }
// One "request": grade a whole college of 50,000 students static int handleRequest(int[] marks) { int passed = 0; for (int m : marks) { if (grade(m) != 'F') passed++; } return passed; }
public static void main(String[] args) { int[] marks = new int[50_000]; for (int i = 0; i < marks.length; i++) { marks[i] = (i * 53) % 101; // fixed pattern, 0 to 100 } for (int req = 1; req <= 8; req++) { long start = System.nanoTime(); int passed = handleRequest(marks); long micros = (System.nanoTime() - start) / 1_000; System.out.println("Request " + req + ": " + micros + " us, passed " + passed); } }}Request 1: 3053 us, passed 30197 Request 2: 1186 us, passed 30197 Request 3: 517 us, passed 30197 Request 4: 545 us, passed 30197 Request 5: 492 us, passed 30197 Request 6: 482 us, passed 30197 Request 7: 477 us, passed 30197 Request 8: 578 us, passed 30197
What this code does
- Every request does the same work and gives the same answer, 30197 students passed. Request 1 took about 3 ms and request 3 onwards about 0.5 ms: the first requests paid for the interpreter and for compiling
gradeandhandleRequest. - On a real results website at 10 am, this is why the first few hundred requests after a deployment are slower. Your numbers will differ by machine and run.
Three things happen in that time. Classes are loaded the first time they are used. Methods run in the interpreter and then in C1 code while the profile is collected. Finally C2 compiles the hottest code, and the speed settles. For a long-running server, warm-up is usually seconds to a minute of slower responses after each restart. That is why teams send some warm-up traffic to a new instance before putting it behind the load balancer.
Why one System.nanoTime measurement misleads
System.nanoTime() returns a time in nanoseconds that is only useful for measuring elapsed time: take it before and after, and subtract. Its unit is nanoseconds, but its real resolution can be coarser; on this Windows machine it moves in steps of 100 ns.
Example 2 · A fairer hand-made timing test
import java.util.Arrays;
public class FairTimingDemo { // Count students who scored 75 or more, from a fixed pattern of marks static int distinctions(int[] marks) { int count = 0; for (int m : marks) { if (m >= 75) count++; } return count; }
static long checksum = 0;
static long timeOnce(int[] marks) { long start = System.nanoTime(); checksum += distinctions(marks); return System.nanoTime() - start; }
public static void main(String[] args) { int[] marks = new int[100_000]; for (int i = 0; i < marks.length; i++) { marks[i] = (i * 37) % 101; // 0 to 100, fixed pattern }
long first = timeOnce(marks); // the cold, first run
for (int i = 0; i < 2_000; i++) { timeOnce(marks); }
long[] runs = new long[21]; for (int i = 0; i < runs.length; i++) { runs[i] = timeOnce(marks); } Arrays.sort(runs);
System.out.println("First (cold) run: " + first / 1_000 + " us"); System.out.println("Fastest warm run: " + runs[0] / 1_000 + " us"); System.out.println("Median warm run: " + runs[runs.length / 2] / 1_000 + " us"); System.out.println("Slowest warm run: " + runs[runs.length - 1] / 1_000 + " us"); System.out.println("Checksum: " + checksum); }}First (cold) run: 2092 us Fastest warm run: 60 us Median warm run: 60 us Slowest warm run: 73 us Checksum: 52050324
What this code does
- The cold first run took 2,092 µs; after 2,000 unmeasured warm-up calls, the median of 21 runs is 60 µs. Reporting the first run would have been off by about 35 times.
- Every result goes into
checksum, which is printed at the end, so the JIT cannot remove the work. The fastest, median and slowest values show how much the warm runs still vary.
One measurement mixes many things: interpreter or compiled code, a compile happening in the background, a GC pause, another program using the CPU. So a single number tells you very little, and comparing two single numbers can point the wrong way. A fairer hand-made test does three things. It warms up first, without measuring. It measures many runs. It reports the median (the middle value after sorting), which a few slow runs cannot drag up the way they drag up an average.
Dead code removal and GC noise in timing tests
Dead code removal is the JIT deleting work whose result is never used. A timing test that calls a method and throws away the result may end up timing an empty loop, and report that the method takes almost no time.
Example 3 · Trap: timing work whose result is thrown away
public class DeadCodeDemo { // Total marks of a big exam: marks follow a fixed pattern from 0 to 99 static int totalMarks(int students) { int total = 0; for (int i = 0; i < students; i++) { total += i % 100; } return total; }
// Flawed: the result is thrown away static long timeIgnored() { long start = System.nanoTime(); totalMarks(10_000); return System.nanoTime() - start; }
// Fair: the result is used, so the work must happen static long checksum = 0;
static long timeUsed() { long start = System.nanoTime(); checksum += totalMarks(10_000); return System.nanoTime() - start; }
public static void main(String[] args) { long ignored = 0; long used = 0; for (int round = 0; round < 20_000; round++) { ignored = timeIgnored(); used = timeUsed(); } System.out.println("Last round, result ignored: " + ignored + " ns"); System.out.println("Last round, result used: " + used + " ns"); System.out.println("Checksum: " + checksum); }}Last round, result ignored: 0 ns Last round, result used: 8700 ns Checksum: 9900000000
What this code does
- Both methods call
totalMarks(10_000). Once C2 has compiledtimeIgnored, it inlinestotalMarks, sees that the result is never used and deletes the loop: the "measurement" is 0 ns, which is just twonanoTimecalls. timeUsedadds the result tochecksum, so the loop must run: about 9 µs for 10,000 students. Whether the JIT removes the work depends on how the code was compiled, which is exactly why hand-made tests are risky.
Example 4 · A program that allocates: shop UPI receipts
import java.util.ArrayList;import java.util.List;
public class ReceiptTiming { // Build one day's UPI receipts for the college shop static int buildReceipts(int count) { List<String> receipts = new ArrayList<>(); for (int i = 0; i < count; i++) { receipts.add("UPI-" + i + " Rs " + (20 + i % 180)); } return receipts.size(); }
public static void main(String[] args) { for (int round = 1; round <= 10; round++) { long start = System.nanoTime(); int n = buildReceipts(200_000); long ms = (System.nanoTime() - start) / 1_000_000; System.out.println("Round " + round + ": " + ms + " ms (" + n + " receipts)"); } }}Round 1: 40 ms (200000 receipts) Round 2: 33 ms (200000 receipts) Round 3: 32 ms (200000 receipts) Round 4: 7 ms (200000 receipts) Round 5: 30 ms (200000 receipts) Round 6: 19 ms (200000 receipts) Round 7: 6 ms (200000 receipts) Round 8: 5 ms (200000 receipts) Round 9: 5 ms (200000 receipts) Round 10: 36 ms (200000 receipts)
What this code does
- The work is identical every round, yet the times jump around: 5 to 7 ms in some rounds and 30 to 40 ms in others, even after warm-up. Round 10 is one of the slowest of all.
- Each round creates 200,000 strings and a growing list, so the garbage collector must run every few rounds. The next example shows the pauses.
Example 5 · GC pauses inside the measured rounds
java -Xlog:gc ReceiptTiming[0.008s][info][gc] Using G1 Round 1: 43 ms (200000 receipts) [0.135s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 26M->22M(118M) 25.768ms Round 2: 36 ms (200000 receipts) [0.164s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 37M->37M(118M) 13.861ms Round 3: 30 ms (200000 receipts) Round 4: 4 ms (200000 receipts) [0.198s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 62M->60M(118M) 21.286ms [0.203s][info][gc] GC(3) Pause Young (Concurrent Start) (G1 Humongous Allocation) 61M->62M(118M) 3.917ms [0.203s][info][gc] GC(4) Concurrent Mark Cycle [0.207s][info][gc] GC(4) Pause Remark 68M->21M(57M) 0.473ms Round 5: 34 ms (200000 receipts) [0.212s][info][gc] GC(4) Pause Cleanup 25M->25M(57M) 0.126ms [0.213s][info][gc] GC(4) Concurrent Mark Cycle 9.869ms [0.228s][info][gc] GC(5) Pause Young (Prepare Mixed) (G1 Evacuation Pause) 36M->34M(171M) 12.566ms Round 6: 20 ms (200000 receipts) Round 7: 5 ms (200000 receipts) Round 8: 6 ms (200000 receipts) Round 9: 5 ms (200000 receipts) [0.278s][info][gc] GC(6) Pause Young (Mixed) (G1 Evacuation Pause) 84M->78M(171M) 28.507ms Round 10: 35 ms (200000 receipts)
What this code does
- Apart from round 1 (warm-up), every slow round has a
Pause Youngline just before its result: round 10 took 35 ms, and 28.5 ms of that was the GC(6) pause. Rounds 7 to 9, with no pause, took 5 or 6 ms. - Using the median hides such outliers, and
-Xlog:gcexplains them. G1 is the default collector on HotSpot for normal server-class machines; the Garbage Collection modules explain these lines.
The fix is to use every result: add it to a checksum field and print the checksum at the end. Then the JIT must do the work. GC noise is time that belongs to the garbage collector, not to your code. Code that allocates objects causes GC pauses now and then, and a pause that lands inside a measured round makes that round look slow. -Xlog:gc shows when pauses happen, so you can see whether a slow round was your code or the collector.
Find the bug
Find the benchmark flaw
Each timing test gives a misleading number. Tap the flawed line, then check the fix.
Time one million square roots.
Round 1 of 3JMH, the OpenJDK benchmark harness, at a glance
JMH (Java Microbenchmark Harness) is the OpenJDK project's tool for measuring small pieces of Java code correctly. It is a separate library, not part of the JDK; you usually create a JMH project with its Maven archetype and run the built benchmarks.jar.
import org.openjdk.jmh.annotations.*;import java.util.concurrent.TimeUnit;@State(Scope.Thread)@BenchmarkMode(Mode.AverageTime)@OutputTimeUnit(TimeUnit.MICROSECONDS)@Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2)public class DistinctionBench { int[] marks = new int[100_000]; @Setup public void fill() { for (int i = 0; i < marks.length; i++) marks[i] = (i * 37) % 101; } @Benchmark public int distinctions() { // returning the result stops dead code removal int c = 0; for (int m : marks) if (m >= 75) c++; return c; }}@Warmupruns iterations that are not counted, so the JIT can finish compiling first.@Forkruns each benchmark in fresh JVMs, so one run's profile and compiled code do not affect another.- Returning a value, or passing it to a
Blackhole, keeps the JIT from removing the work as dead code. - JMH reports a score with an error range across iterations and forks, not one lucky number.
Startup help: class data sharing
Class data sharing (CDS) lets the JVM load core JDK classes from a ready-made archive file instead of reading and parsing each class file at startup. The JDK ships a default archive, and since Java 12 CDS is on by default (-Xshare:auto).
Example 6 · Seeing class data sharing at work
java -Xlog:class+load ResultsServerDemojava -Xshare:off -Xlog:class+load ResultsServerDemojava -Xlog:class+load ResultsServerDemo | grep -c "shared objects file"java -Xshare:off -Xlog:class+load ResultsServerDemo | grep -c "shared objects file"$ java -Xlog:class+load ResultsServerDemo [0.044s][info][class,load] java.lang.Object source: shared objects file ... [0.102s][info][class,load] ResultsServerDemo source: file:/.../ ... $ java -Xshare:off -Xlog:class+load ResultsServerDemo [0.077s][info][class,load] java.lang.Object source: jrt:/java.base ... [0.390s][info][class,load] ResultsServerDemo source: file:/.../ ... $ java -Xlog:class+load ResultsServerDemo | grep -c "shared objects file" 583 $ java -Xshare:off -Xlog:class+load ResultsServerDemo | grep -c "shared objects file" 0
What this code does
- With CDS,
java.lang.Objectand 582 other JDK classes came from theshared objects file, the CDS archive. With-Xshare:offevery class is read fromjrt:/java.baseinstead. Your own class always comes from its class file unless you build an AppCDS archive. - The time stamps differ from run to run on a busy laptop, so do not read too much into one pair. Measure startup over many runs if it matters. Program output and most log lines are trimmed with
....
The sharing word in java -version output means it is in use. CDS helps startup time and memory, because the archive is mapped into memory and can be shared by several JVMs on one machine. It does not compile anything: hot code still warms up through the interpreter and the JIT.
You can also archive your own application's classes. Since Java 13, -XX:ArchiveClassesAtExit=app.jsa writes such an archive at the end of a run, and -XX:SharedArchiveFile=app.jsa uses it next time. This is called AppCDS.
Next step
Check your understanding
12 quick questions