Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating time difference in Milliseconds

Tags:

java

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.

like image 249
arsenal Avatar asked Mar 14 '12 18:03

arsenal


People also ask

How do you find the difference between two times with milliseconds?

You can use DiffSeconds() built-in function and multiply the result by 1000. The output will be milliseconds.

How do you calculate time in milliseconds?

To convert a second measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the seconds multiplied by 1,000.

How do I calculate time difference between milliseconds on Excel?

There is also an elegant alternative to this solution: You can simply multiply the time value by 86400000 to convert it into milliseconds. This works because of the internal numeric format used by Excel where 1 is equal to 24h = 24h × 60min/h × 60s/min × 1000ms/s = 86400000ms.

How do you calculate time difference?

To calculate the time difference in minutes, you need to multiply the resulting value by the total number of minutes in a day (which is 1440 or 24*60). Suppose you have a data set as shown below and you want to calculate the total number of minutes elapsed between the start and the end date.


7 Answers

Try this

long start_time = System.nanoTime();
resp = GeoLocationService.getLocationByIp(ipAddress);
long end_time = System.nanoTime();
double difference = (end_time - start_time) / 1e6;
like image 193
endbegin Avatar answered Oct 05 '22 10:10

endbegin


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

like image 42
Campa Avatar answered Oct 05 '22 10:10

Campa


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

like image 32
Jon Skeet Avatar answered Oct 05 '22 08:10

Jon Skeet


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.

like image 25
Erik Ekman Avatar answered Oct 05 '22 09:10

Erik Ekman


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));
like image 39
user2173372 Avatar answered Oct 05 '22 10:10

user2173372


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.

like image 23
AlexR Avatar answered Oct 05 '22 08:10

AlexR


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.

like image 26
BillS Avatar answered Oct 05 '22 08:10

BillS