Search code examples
javaperformancenanotime

How to get a meaningful result from subtracting 2 nanoTime objects?


I created a filter that monitors the length of a request.

long start = System.nanoTime();

...

long end = System.nanoTime();

How can I get the number of milliseconds from this now?


Solution

  • (end - start) / 1000000
    

    1 microsecond = 1000 nanoseconds

    1 millisecond = 1000 microseconds

    Note, that the result will be rounded down, but you usually don't get true nanosecond accuracy anyway (accuracy depends on the OS). From the Javadoc on nanoTime():

    This method provides nanosecond precision, but not necessarily nanosecond accuracy.