Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I measure time elapsed in Java? [duplicate]

Tags:

java

time

I want to have something like this:

public class Stream {     public startTime;     public endTime;      public getDuration()     {         return startTime - endTime;     } } 

Also it is important that for example if the startTime it's 23:00 and endTime 1:00 to get a duration of 2:00.

Which types to use in order to accomplish this in Java?

like image 590
Omu Avatar asked Nov 20 '09 11:11

Omu


People also ask

How do you measure elapsed time?

In simple words, we can say that the amount of time that has passed between the beginning and the end of an event is called the elapsed time. We can determine this time by subtracting the end time and the start time. The formula to calculate the elapsed time is simply to subtract the hours and minutes separately.

What are used to measure the elapsed time of event?

Per the Android docs SystemClock. elapsedRealtime() is the recommend basis for general purpose interval timing. As others have said, the elapsedRealtime() answer below is correct.

How do you record seconds in Java?

To compute the elapsed time of an operation in seconds in Java, we use the System. currentTimeMillis() method.


1 Answers

Unfortunately, none of the ten answers posted so far are quite right.

If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime(). You cannot use System.currentTimeMillis(), unless you don't mind your result being wrong.

The purpose of nanoTime is to measure elapsed time, and the purpose of currentTimeMillis is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there's a process that runs and continually issues small corrections to the system clock ("wall clock"). These tend to happen often. Another such correction happens whenever there is a leap second.

Since nanoTime's purpose is to measure elapsed time, it is unaffected by any of these small corrections. It is what you want to use. Any timings currently underway with currentTimeMillis will be off -- possibly even negative.

You may say, "this doesn't sound like it would ever really matter that much," to which I say, maybe not, but overall, isn't correct code just better than incorrect code? Besides, nanoTime is shorter to type anyway.

Previously posted disclaimers about nanoTime usually having only microsecond precision are valid. Also it can take more than a whole microsecond to invoke, depending on circumstances (as can the other one), so don't expect to time very very small intervals correctly.

like image 92
Kevin Bourrillion Avatar answered Sep 23 '22 22:09

Kevin Bourrillion