49

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.

4
  • 2
    Maybe you have a fast connection?
    – user851031
    Mar 14, 2012 at 18:32
  • Just System.out.println both the times, and see what you get. Mar 14, 2012 at 18:34
  • The time in milli-seconds could be 0. If its faster than 1 ms do you care, if so use System.nanoTime() otherwise don't worry about it. ;) Mar 14, 2012 at 18:39
  • You're measuring the time it's taking to assign properties without actually doing anything to them. That's going to be friggin fast!
    – ingyhere
    Dec 16, 2013 at 5:27

9 Answers 9

63

Try this

long start_time = System.nanoTime();
resp = GeoLocationService.getLocationByIp(ipAddress);
long end_time = System.nanoTime();
double difference = (end_time - start_time) / 1e6;
4
  • 12
    Programming conventions are personal choices. Comments about how people stylize their code don't belong in Stackoverflow.
    – Johann
    Feb 12, 2013 at 14:01
  • 20
    @AndroidDev, but conventions are not personal choices and side comments about style are helpful to new developers and thus belong on stackoverflow. Just like driving the speed limit isn't a personal choice. Sure you can drive 20 in a 60, but you'll upset everyone along the way and may cause an accident. Oct 16, 2013 at 16:00
  • 1
    @endbegin did you mean "1e9"? nanosecond is 10^(-9) afaik.
    – Leonz
    Oct 4, 2016 at 18:35
  • @Leonz OP had difference measured in millis. endbegin went with that (IMO quite properly)
    – user719662
    Jul 18, 2017 at 22:02
51

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

0
14

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.)

4
  • Ok. So any way to measure this thing if the difference is 0?
    – arsenal
    Mar 14, 2012 at 18:33
  • This is totally backwards. Straight from the Javadoc for System.nanoTime: "This method provides nanosecond precision, but not necessarily nanosecond resolution. ... The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed." I can further state that it works crummy last time I tried it on Windows. C programmers would love the answer above!!!
    – ingyhere
    Dec 16, 2013 at 5:11
  • 1
    @ingyhere: I'm not sure what you're trying to say - the code in my answer (and indeed in the question) clearly is obtaining two values within the same instance of a Java virtual machine. What exactly do you think is "totally backwards"? What do you mean by "it works crummy" exactly?
    – Jon Skeet
    Dec 16, 2013 at 6:43
  • (From Javadoc) Precision, but not necessarily nanosecond resolution. That means to me it's not accurate. And, it clearly states it works different in different JVMs. What good are clocks that work differently in different places? As to the "crummy" I'm not referring to your code but to the "System.nanoTime()" call, which was providing chunky values last time I tried it in Windows.
    – ingyhere
    Dec 18, 2013 at 2:11
5

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));
4

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.

2
  • 1
    Nanotime is not a "time" as such but yes, is the best thing to use for elapsed times within one Java VM.
    – Jon Story
    Sep 25, 2015 at 13:38
  • Beware that you are not necessarily getting nanosecond-by-nanosecond as conventional hardware clocks are not that fine in their accuracy. Per the class doc: This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) Feb 10, 2018 at 4:30
1

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.

1

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.

0

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

System.nanoTime()
0

You can use System.nanoTime();

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.