What the difference between currentTimeMillis and nanoTime in Java?
There are two similar methods in Java: System.currentTimeMillis()
and System.nanoTime()
that relate to time measurement. CurrentTimeMillis returns the current time in milliseconds from the Epoch (January 1, 1970, 00:00:00 GMT) and nanoTime returns a nanosecond-precision time related to some elapsed time. So you can measure time intervals using both methods but estimate offset related to common begin only with System.currentTimeMillis()
. Let’s go deeper..
Lets specify levels of difference:
- Estimated value | Epoch time vs Escaped time
- Estimation unit | Millis vs Nanos
- Clock type | Realtime vs Monotonic
Under the hood HotSpot JVM (for POSIX) use clock_gettime
(https://linux.die.net/man/3/clock_gettime) with two different arguments:
- CLOCK_REALTIME for
System.currentTimeMillis()
- CLOCK_MONOTONIC for
System.nanoTime()
jlong os::javaTimeMillis() {
struct timespec ts;
int status = clock_gettime(CLOCK_REALTIME, &ts);
assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
return jlong(ts.tv_sec) * MILLIUNITS +
jlong(ts.tv_nsec) / NANOUNITS_PER_MILLIUNIT;
}
jlong os::javaTimeNanos() {
struct timespec tp;
int status = clock_gettime(CLOCK_MONOTONIC, &tp);
assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
jlong result = jlong(tp.tv_sec) * NANOSECS_PER_SEC + jlong(tp.tv_nsec);
return result;
}
You can find this in https://github.com/openjdk/jdk/blob/4f529f8c232b4082aa4aa39766bcf42b09885ee4/src/hotspot/os/posix/os_posix.cpp#L1412
As we know the difference between CLOCK_REALTIME and CLOCK_MONOTONIC:
CLOCK_REALTIME
System-wide realtime clock. Setting this clock requires appropriate privileges.CLOCK_MONOTONIC
Clock that cannot be set and represents monotonic time since some unspecified starting point.
[Linux Die Net]
And also:
Another difference is CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.
[StackOverflow]
What is more important is that CLOCK_MONOTONIC are guaranteed to be monotonic only on the same core.
Mark Andreev, SWE @ Conundrum AI