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.
Related
I'm currently trying to implement progress of a long running process in Java.
Based on the current logic I'm trying to calculate approximate time when the program going to end based on using the time taken for single unit of calculation. For ex: I'm running a invoice progress to be sent to multiple vendors and each invoice takes 10s. So based on this I'll calculate the time for rest of the pending invoices.
I'm keeping the start time in milliseconds.
long startmillis = System.currentTimeMillis();
long finishmillisforsingleVendor = System.currentTimeMillis();
long elapsedTime = finishmillisforsingleVendor - startmillis;
long approximateEndTime = elapsedTime/1000 * 25;// trying to calculate in seconds and multiply with 25 remaining invoices.
This is the part I'm not sure. How would I use this elapsed time for single invoice to derive my program end time.
long percentageCompleted = System.currentTimeMillis()/1000 / approximateEndTime ;
I'm trying to calculate the percentage at any given point of time to show the user how much has been progressed so far. I'm not sure if this the right way to go.
Thanks
From the way you phrased your question, I suspect you're confusing a few terms. The percentage completed has nothing to do with elapsed time.
double percentComplete = 100.0*numberOfDocumentsCompleted/totalNumberOfDocuments;
Though, instead of a percentage, I would prefer a simple ratio:
double completionStatus = (double)numberOfDocumentsCompleted/totalNumberOfDocuments;
long elapsedMillis = System.currentTimeMillis() - startMillis;
long estimatedTotalMillis = (long) (elapsedMillis / completionStatus);
long remainingMillis = estimatedTotalMillis - elapsedMillis;
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´m working on a 2d java game but I´m stuck on timer problems. Here is my game loop:
void gameLoop(isRunning){
....
doStuff();
....
}
I have a fps measuring code like this inside the loop:
long thisLoop = System.currentTimeMillis();
delta = thisLoop - lastLoopTime;
lastLoopTime = thisLoop;
So I get how much time has passed since last loop. However, whenever I try to use System.nanoTime() instead of System,currentTimeMillis() like this:
long thisLoop = System.nanoTime();
delta = thisLoop - lastLoopTime;
lastLoopTime = thisLoop;
My game gets completely screwed, doesn't render anything past first frame, no errors reported just frozen. I´m on win 7 64 lastest java 1.6. What could be wrong?
Try using System.nanoTime() / 1000000 since it's in nanoseconds instead of milliseconds like you're probably expecting.
Are you multiplying or dividing by 1,000,000? 1 millisecond = 1 000 000 nanoseconds. I'm assuming that the rest of your logic is implemented in terms of milliseconds.
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.