What is the unit of the difference of two System.currentTimeMillis ?
start = System.currentTimeMillis();
longoperation();
elapsedTime = System.currentTimeMillis() - start;
What is the unit of elapsed time here. It doesn't look like milliseconds.
Is the above code segment the right way to find the time taken to execute longoperation()?
Yes, it is in milliseconds. Bear in mind that the difference is not absolutely correct and may vary.
It is ms (MiliSecond) only, you are doing right.
You can ignore time taken while calculating millis
It is milliseconds and your code looks correct.
Whatever you are doing is correct. If you want the time in seconds, simply divide it by 1000.
long start = System.currentTimeMillis();
longoperation();
long elapsedTime = (System.currentTimeMillis() - start)/1000;
Yes, currentTimeMillis() returns you a milliseconds value.
On Windows, it used to be the case that the returned value had quite low resolution, and so was only accurate to something like 10ms. I'm not certain whether this is still the case as I haven't used Windows for a few years - but if your longoperation() actually takes just a few millis, and you're running on Windows, then you may see elapsedTime variously being 10ms or 0ms.
Related
I am recently working with an algorithm and implementing it in JAVA. In which I put a timer for computing the time taken by particular phase of algorithm. The code for timer is something like this.
static long start = 0;
long time = System.currentTimeMillis() - start;
System.out.printf("Took %.3f%n", time/1e3);
And the output of this code is
Took 6.807
Now what is the unit of time in this output. Is it millisecond or microsecond or nano second or just second? And what needs to be done with this code to get the output time in millisecond? Thank You in advance.
Here is the explanation:
System.currentTimeMillis() returns the current time in milliseconds. Check the link.
Dividing it with 1e3 (it's 1*103, that's 1000) converts the time to seconds, because one second contains 1000 milliseconds.
However I don't understand the usage of the key word static in the first line.
This question already has answers here:
How do I write a correct micro-benchmark in Java?
(11 answers)
Closed 9 years ago.
I need to analyze complexity for some algorithms in Java. For that I am planning to give large number of input and measure the time taken by Java implementation. What is the most precise and accurate way to check time between some lines of code? I need precision in milliseconds...
You can get nanosecond resolution, even, using System.nanoTime().
However, you may want to consider the points in the following:
How do I write a correct micro-benchmark in Java?
Use a library such as Speed4j. This shall not only benchmark the calls but also provide statistics in logs, also you can see them remotely via JMX. It is better of using such a library rather than placing System.current.. calls all over the code.
Say you have a particular method that you would like to put under the microscope. You can do that as follows:
long time1 = System.nanoTime();
thatMethod();
long time2 = System.nanoTime();
long timeTaken = time2 - time1;
System.out.println("Time taken " + timeTaken + " ns");
Computers are really fast so it may happen that time difference when using getTimeMillis() maybe zero. Hence, use nanoTime()
You can also use Caliper. They have a video to get started. Plus, thoroughly read the answer pointed to by creichen. It has a lot of great stuff in it.
Use System.nanoTime() or System.currentTimeMillis() to get both start and finish time of your code. Be aware that micro-benchmarks measure only basic aspects of JVM performance. Be aware of warm up phase for JVM, after which JIT is started.
long start = System.currentTimeMillis();
// your code
long end = System.currentTimeMillis();
long diff = end-start;
or
long start = System.nanoTime();
// your code
long end = System.nanoTime();
long diff = end-start;
long diffInMillis = diff/1000000;
long startTime = System.currentTimeMillis();
//code lines whose time you want to calculate
long endTime = System.currentTimeMillis();
System.out.println("Took "+(endTime - startTime) + " ms");
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.
Try this
long start_time = System.nanoTime();
resp = GeoLocationService.getLocationByIp(ipAddress);
long end_time = System.nanoTime();
double difference = (end_time - start_time) / 1e6;
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
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.)
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.
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));
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.
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.
In such a small cases where difference is less than 0 milliseconds you can get difference in nano seconds as well.
System.nanoTime()
You can use
System.nanoTime();
To get the result in readable format, use
TimeUnit.MILLISECONDS or NANOSECONDS
I am reading the system time just before the method is invoked and immediately after method returns and taking the time difference, which will give the time taken by a method for execution.
Code snippet
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println ("Time taken for execution is " + (end - start));
The strange thing is the output is 0..how is this possible..?
Chances are it's taking a shorter time than the fairly coarse-grained system clock. (For example, you may find that System.currentTimeMillis() only changes every 10 or 15 milliseconds.)
System.currentTimeMillis is good for finding out the current time, but it's not fine-grained enough for measuring short durations. Instead, you should use System.nanoTime() which uses a high-resolution timer. nanoTime() is not suitable for finding the current time - but it's designed for measuring durations.
Think of it as being the difference between a wall clock and a stopwatch.
use nanoTime()
Because it took less than 1 millisecond?
If you want to get a more meaningful metric, I would suggest calling your method in a loop 1000000 times, timing that, and then dividing by 1000000.
Of course, even then, that might not be representative; the effects on the cache will be different, etc.
I want to compare the performance of certain operations in my application.
Other than using the Date object, is there anything more precise?
public static long nanoTime() - Returns the current value of the most precise available system timer, in nanoseconds.
As Zach Scrivener states in his answer:
My guess is that since System.nanoTime() uses the "most precise
available system timer" which apparently only has
millisecond-precision on your system, you can't get anything better.
If you're measuring elapsed time by subtracting two timestamps, you should use System.nanoTime() to get those timestamps. That's what it's for.
To get the CPU time you can use the getCurrentThreadCpuTime of the Thread Management Bean.
It returns the CPU time used by the actual thread in nanoseconds:
ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
long time = threadMX.getCurrentThreadCpuTime();
// do something
time = threadMX.getCurrentThreadCpuTime() - time; // CPU time in nanoseconds
check the documentation for details and some problems like CPU time measurement not being enabled.