Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Which Java clock should you use to measure how long a method takes: System.currentTimeMillis(), System.nanoTime() or Instant.now()? Show correct code and explain why the others can give wrong results.

To measure how long a method takes we use System.nanoTime(): take a reading before, a reading after, and subtract, then wrap the difference in Duration.ofNanos for display. nanoTime is a monotonic clock meant for intervals, so it never jumps. System.currentTimeMillis() and Instant.now() follow the wall clock, which can be moved forwards or backwards by NTP or an operator, so durations computed from them can come out negative or inflated; they are for timestamps, not durations.

Why this question is asked

Timing code looks trivial, and that is why it is often done wrong. A wrong clock gives numbers that are fine on a developer laptop and then, once a month in production, report that a request took minus three seconds or exactly one hour. Those numbers end up in dashboards, alerts and performance decisions. Interviewers ask this question to see whether we know that Java has two very different kinds of clock and which one fits which job. In this answer, we will recap the two kinds of clock, write the correct timing code, see exactly how the wall clock produces wrong durations, and finish with what to use in production.

1A Quick Recap: Wall Clocks and Monotonic Clocks

A computer keeps two different notions of time. The wall clock is the time of day, the one we would read from a clock on the wall: 2026-11-04 10:15:00 UTC. It is meant to agree with the real world, so the operating system keeps correcting it. NTP, the Network Time Protocol, compares the machine's clock with time servers and adjusts it, sometimes by slowly speeding it up or slowing it down and sometimes by stepping it straight to the right value. An administrator, a virtual machine resuming from a pause, or a container host can move it too.

A monotonic clock is a counter that only ever moves forward at a steady rate since some arbitrary starting point, often when the machine booted. It does not know what time of day it is, and nobody corrects it to match the outside world. That makes it useless for saying when something happened, but perfect for saying how long something took.

In Java, System.currentTimeMillis() and Instant.now() read the wall clock. System.nanoTime() reads a monotonic clock.

Java clocks and what they are for
CallKind of clockCan jump?Use it for
System.currentTimeMillis()wall clock, ms since 1970 UTCyes, NTP or manual changestimestamps
Instant.now()wall clock, as an Instantyes, same clocktimestamps, stored as UTC
System.nanoTime()monotonic, arbitrary originno, only moves forwardelapsed time in one JVM

2Writing the Timing Code Correctly

The pattern is to read nanoTime before the work, read it again after, and subtract. The result is a long number of nanoseconds. To show it to a person we convert it to a Duration, which prints in a readable ISO format and converts to milliseconds or seconds without manual arithmetic.

Java
long start = System.nanoTime();
work();
long tookNanos = System.nanoTime() - start;
Duration took = Duration.ofNanos(tookNanos);
System.out.println(took); // PT0.250731402S
System.out.println(took.toMillis()); // 250
System.out.println(System.nanoTime()); // 81243516722841 (meaningless on its own)

Notice the last line. The value nanoTime returns has no meaning by itself; it is not the time since 1970 and it is not related to the date. Only the difference between two readings in the same JVM means anything. So we must never store a nanoTime value in a database, send it to another service, or compare it with a value from another process: their origins are different and the comparison is nonsense.

One more detail matters for very long intervals. Because the counter can in principle start at any value, including a large one close to overflow, we compare readings by subtracting them, as above, and never with start < end. Subtraction gives the right answer even across an overflow, while a direct comparison does not.

3How the Wall Clock Produces Wrong Durations

Now let us see what goes wrong with the wall clock. Suppose the machine's clock has drifted two seconds ahead, and NTP steps it back just while our method is running.

Java
long start = System.currentTimeMillis(); // 10:15:00.000 (clock is 2 s fast)
work(); // takes 500 ms; meanwhile NTP steps clock back 2 s
long took = System.currentTimeMillis() - start;
System.out.println(took); // -1500 (a negative duration)
Instant s = Instant.now();
work(); // takes 500 ms; meanwhile clock is stepped forward 1 h
System.out.println(Duration.between(s, Instant.now()).toMillis()); // 3600500

The reason is that both readings come from a clock that someone was allowed to move. The subtraction measures not only the work but also every correction applied in between. A step back gives a negative or too-small result, and a step forward adds the step size to the result. With nanoTime, the same 500 ms of work measures 500 ms no matter what happens to the time of day, because nobody adjusts the monotonic counter.

There is also a resolution problem. currentTimeMillis has at best millisecond precision, and on some systems it advances in coarser steps, so very short methods often measure as 0. nanoTime is designed for fine-grained intervals, which makes it the natural choice even when no clock jump happens.

4Wall-Clock Values Still Have Their Job

None of this makes Instant.now() a bad API. When we need to record when something happened, for an audit log, an order timestamp or a token expiry, we want the wall clock, because that is the time that people and other systems agree on. We store it as an Instant, which is UTC. The rule is simple: wall clock for when, monotonic clock for how long. If we need both, we take both readings: an Instant for the start timestamp and a nanoTime for the duration.

5In Production, Let a Metrics Library Time It

Hand-written timing with nanoTime is fine for a quick experiment, but in a real service we want percentiles, histograms and dashboards, not log lines. Micrometer, which Spring Boot uses for its metrics, gives us a Timer that uses a monotonic clock internally and records the result in a form monitoring systems understand.

Java
Timer timer = Timer.builder("import.file").register(registry);
timer.record(() -> work()); // time a block
Timer.Sample sample = Timer.start(registry); // or start and stop separately
work();
sample.stop(timer); // records the elapsed time

For benchmarking a method in isolation, as opposed to measuring it in production, neither hand timing nor a Timer is enough, because of JIT warm-up and dead-code elimination. That is the job of JMH, the Java Microbenchmark Harness, which runs warm-up iterations and controls those effects for us.

6Follow-up questions

What is the resolution of nanoTime in practice?

The value is in nanoseconds, but the guarantee is only that the resolution is at least as good as currentTimeMillis. On modern Linux, macOS and Windows machines, nanoTime is backed by a high-resolution hardware counter, and successive calls typically differ by tens of nanoseconds, while a single call itself costs around 20 to 30 nanoseconds on common hardware. So it is excellent for measuring things that take microseconds or more, but it cannot meaningfully time a handful of instructions; for that we use JMH, which repeats the operation many times.

Can I compare nanoTime values across threads?

Yes, within the same JVM. All threads read the same monotonic clock, so a reading on one thread and a reading on another can be subtracted. What we cannot do is compare values across different JVMs or machines, or across a restart of the same JVM.

Why not use Instant.now() and just discard negative values?

Because the negative values are only the visible part of the error. A forward step makes durations too large, and a slow NTP slew makes every duration slightly wrong, and neither shows up as an obviously bad number. Dropping negatives hides the symptom while the data stays wrong.

7Conclusion

In this answer, we saw that Java has wall-clock methods, currentTimeMillis and Instant.now, and a monotonic method, nanoTime. Elapsed time must come from nanoTime, by subtracting two readings in the same JVM and wrapping the result in a Duration, because the wall clock can be stepped by NTP or an operator and then gives negative or inflated durations. Wall-clock values remain right for timestamps, and in production we let Micrometer's Timer do the measuring.

What to say in the interviewAbout 90 seconds aloud

Open with

I would use System.nanoTime. I take long start = System.nanoTime() before the call, subtract it from another nanoTime reading after, and wrap the result in Duration.ofNanos if I need to print or convert it. nanoTime is a monotonic clock: it only moves forward at a steady rate and nobody adjusts it, so it is meant for measuring intervals.

Then, if they want more

Its absolute value means nothing, so I never store it or compare it across JVMs, only subtract two readings from the same process. currentTimeMillis and Instant.now read the wall clock, the time of day.

The operating system keeps correcting that clock, NTP can step it back or forward, an administrator can change it, a VM can resume after a pause, and if that happens while my method runs, the difference includes the correction.

That is how you get negative durations, or one that is too long by exactly the size of the step. currentTimeMillis also has only millisecond resolution, so short methods measure as zero. The wall clock is still the right choice for timestamps, when something happened, which I store as an Instant in UTC.

In a real service I would not hand-write the timing at all; I would use a Micrometer Timer, which uses a monotonic clock and gives percentiles on the dashboard, and for micro-benchmarks I would use JMH.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Which Java clock should you use to measure how long a method takes...": https://scrivio-interview-library.netlify.app/java/date-and-time/546b9a3000/