[java] Calculating time difference in Milliseconds

I am making a call to a method by passing ipAddress and it will return back the location of ipAddress like Country, City, etc etc. So I was trying to see how much time it is taking for each call. So I set the start_time before making call to method and end_time after making a call. So sometimes I get difference as 0. And resp contains the valid response.

long start_time = System.currentTimeMillis();
resp = GeoLocationService.getLocationIp(ipAddress);
long end_time = System.currentTimeMillis();
long difference = end_time-start_time;

So that means sometimes it is taking 0 ms to get the response back. Any suggestions will be appreciated.

This question is related to java

The answer is


No, it doesn't mean it's taking 0ms - it shows it's taking a smaller amount of time than you can measure with currentTimeMillis(). That may well be 10ms or 15ms. It's not a good method to call for timing; it's more appropriate for getting the current time.

To measure how long something takes, consider using System.nanoTime instead. The important point here isn't that the precision is greater, but that the resolution will be greater... but only when used to measure the time between two calls. It must not be used as a "wall clock".

Note that even System.nanoTime just uses "the most accurate timer on your system" - it's worth measuring how fine-grained that is. You can do that like this:

public class Test {
    public static void main(String[] args) throws Exception {

        long[] differences = new long[5];
        long previous = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            long current;
            while ((current = System.nanoTime()) == previous) {
                // Do nothing...
            }
            differences[i] = current - previous;
            previous = current;            
        }

        for (long difference : differences) {
            System.out.println(difference);
        }
    }
}

On my machine that shows differences of about 466 nanoseconds... so I can't possibly expect to measure the time taken for something quicker than that. (And other times may well be roughly multiples of that amount of time.)


In such a small cases where difference is less than 0 milliseconds you can get difference in nano seconds as well.

System.nanoTime()

In the old days (you know, anytime before yesterday) a PC's BIOS timer would "tick" at a certain interval. That interval would be on the order of 12 milliseconds. Thus, it's quite easy to perform two consecutive calls to get the time and have them return a difference of zero. This only means that the timer didn't "tick" between your two calls. Try getting the time in a loop and displaying the values to the console. If your PC and display are fast enough, you'll see that time jumps, making it look as though it's quantized! (Einstein would be upset!) Newer PCs also have a high resolution timer. I'd imagine that nanoTime() uses the high resolution timer.


I do not know how does your PersonalizationGeoLocationServiceClientHelper works. Probably it performs some sort of caching, so requests for the same IP address may return extremely fast.


Since Java 1.5, you can get a more precise time value with System.nanoTime(), which obviously returns nanoseconds instead.

There is probably some caching going on in the instances when you get an immediate result.


I pretty much like the (relatively) new java.time library: it's close to awesome, imho.

You can calculate a duration between two instants this way:

import java.time.*

Instant before = Instant.now();
// do stuff
Instant after = Instant.now();
long delta = Duration.between(before, after).toMillis(); // .toWhatsoever()

API is awesome, highly readable and intuitive.

Classes are thread-safe too. !


References: Oracle Tutorial, Java Magazine


From Java 8 onward you can try the following:

import java.time.*;
import java.time.temporal.ChronoUnit;

Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();

System.out.println(Duration.between(start_time, stop_time).toMillis());

//or

System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));

You can use System.nanoTime();

To get the result in readable format, use TimeUnit.MILLISECONDS or NANOSECONDS