Is System.nanoTime() a constant time operation?

Viewed 81

I’m trying to track down the native code for System’s nanoTime() method. I’m particularly interested in knowing whether it’s a constant time operation. Incidentally, I’m also curious to know how one might measure the time it takes for the method to execute.

EDIT:

I’m aware that any question of the method being constant time relies on there being some ‘n’ value. I don’t know how the method works, so was wondering if there might be some ‘n’ value upon which the method depends, written in the code. Any pointers towards the native code would be great.

1 Answers

Reading a CPU counter can be considered constant time. Easiest is to check the source code of the JVM:

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;
}

Now, there's no loop and no input to this function. Since it doesn't depend on any input, there's no N with which the function execution can grow.

How is clock_gettime implemented? Again, look at the source

Related