Stop Using currentTimeMillis! 90% of Java Developers Miscalculate Time
The article explains why System.currentTimeMillis() is unsuitable for measuring code execution duration, demonstrates its non‑monotonic behavior and potential for negative results, and shows that System.nanoTime() provides a reliable, high‑resolution, monotonic timer for accurate performance analysis.
Two Different Kinds of Time in Java
Java provides two primary time‑related methods: System.currentTimeMillis() and System.nanoTime(). Although both return long values, their semantics differ fundamentally.
System.currentTimeMillis(): Calendar Time
This method returns the number of milliseconds elapsed since the Unix epoch (1970‑01‑01 00:00:00 UTC). It reflects the operating system’s wall‑clock time and is suitable for logging, timestamps, and displaying the current date.
However, the value is not monotonic because the system clock can be adjusted by NTP synchronization, manual changes, VM/container time calibration, or daylight‑saving shifts. If the clock moves forward or backward while measuring a duration, the computed interval ( end - start) may be too large, too small, or even negative, violating the notion of elapsed time.
System.nanoTime(): JVM’s High‑Resolution Stopwatch
System.nanoTime()is designed solely for measuring elapsed time. It does not represent a real‑world date, has no fixed epoch, and guarantees a strictly monotonic increase as long as the JVM runs. It is unaffected by system‑time adjustments.
Key characteristics:
Does not map to a calendar date.
Has no business‑meaningful start point.
Ensures monotonic increase.
Unaffected by clock changes.
Typical usage example:
long start = System.nanoTime();
// code to measure
long elapsedNanos = System.nanoTime() - start;
double elapsedMillis = elapsedNanos / 1_000_000.0;
System.out.println("Elapsed: " + elapsedMillis + " ms");Two important rules:
Only compare differences between nanoTime calls.
Do not store nanoTime values as timestamps.
Precision and Stability
On many systems, currentTimeMillis() advances in steps of 10–15 ms, while nanoTime() offers much finer granularity. For methods that run only 2–3 ms, high‑frequency interfaces, or concurrent logic, currentTimeMillis() often yields meaningless results.
Use milliseconds for absolute timestamps; use nanoseconds for measuring intervals.
Why java.util.Timer Is Not a Timing Tool
People often confuse Timer with nanoTime. java.util.Timer is a scheduler that decides *when* a task should run, not *how long* it took. It solves the problem of “when to execute?” whereas nanoTime answers “how long did it take?”. Comparing the two is like comparing a calendar with a stopwatch.
Correct mapping:
Scheduling → Timer / ScheduledExecutorService Duration measurement →
System.nanoTime()Recommended Duration‑Measurement Example
A concise, production‑ready snippet:
package com.icoderoad.timing;
public class ExecutionTimer {
public static void main(String[] args) {
long startNano = System.nanoTime();
// Simulate business logic
mockBusinessLogic();
long elapsedNano = System.nanoTime() - startNano;
double elapsedMillis = elapsedNano / 1_000_000.0;
System.out.println("Code execution time: " + elapsedMillis + " ms");
}
private static void mockBusinessLogic() {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}Sample output:
Code execution time: 2.347 ms
The result remains stable and trustworthy even if the system clock is altered.
Final Thoughts
Many bugs stem from choosing the wrong time‑semantic model. System.currentTimeMillis() itself is fine for real‑world timestamps; the mistake is using it to measure durations. Use System.currentTimeMillis() for wall‑clock time and System.nanoTime() for accurate execution‑time measurement. This distinction is an engineering correctness issue, not merely a coding‑style preference.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
LuTiao Programming
LuTiao Programming is a friendly community offering free programming lessons. We inspire learners to explore new ideas and technologies and quickly acquire job-ready skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
