How to Calculate the Elapsed Time of an Event in Java

How do I calculate the elapsed time of an event in Java?

I would avoid using System.currentTimeMillis() for measuring elapsed time. currentTimeMillis() returns the 'wall-clock' time, which may change (eg: daylight savings, admin user changing the clock) and skew your interval measurements.

System.nanoTime(), on the other hand, returns the number of nanoseconds since 'some reference point' (eg, JVM start up), and would therefore not be susceptible to system clock changes.

how to calculate the elapsed time of a particular event in my application?

Here is an example on how to count days, you can add hours and mins to this.

            long MILLIS_IN_DAY = 1000 * 60 * 60 * 24;

String lastEvent = "13.07.2013 10:20:06";
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
Date lastEventDate = sdf.parse(lastEvent);
Date currentDate = new Date();

long timeElapsed = currentDate.getTime() - lastEventDate.getTime();
long diffInDays = timeElapsed / MILLIS_IN_DAY;

System.out.println(diffInDays);

How do I measure time elapsed in Java?

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.

How to measure elapsed time

When the game starts:

long tStart = System.currentTimeMillis();

When the game ends:

long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;

How do I time a method's execution in Java?

There is always the old-fashioned way:

long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.

Measure elapsed time between two MotionEvents in Android

long startTime;
public boolean onTouchEvent(MotionEvent event) {

if (event.getAction() == MotionEvent.ACTION_DOWN)
startTime = System.nanoTime();

else if (event.getAction() == MotionEvent.ACTION_UP) {
long elapseTime = System.nanoTime() - startTime;
//do whatever u want with elapseTime now, its in nanoseconds
}
}

How to calculate the time difference between two events in Java?

You can use System.currentTimeMillis() to save the current time at one millisecond resolution.
Just save the time whenever the first event occurs (better use a long var to hold that value)
and again when the 2nd event occurs. The difference divided by 1000 will give you time difference in seconds.

Elapsed time between first and second ACTION_DOWN

For this you need to create Custom Gesture Detector and initialize your interface for single Click,Double Click,long pressed .For Simplicity ,
Here is your code :

img.setOnTouchListener(new MyTouchDetector(mContext,this));

public class MyTouchDetector extends GestureDetector.SimpleOnGestureListener implements View.OnTouchListener {
int position;
private Context mContext;
private GestureDetector mGestureDetector;
private ClickDetector clickDetector;

public MyTouchDetector(Context mContext, ClickDetector clickDetector) {
this.mGestureDetector = new GestureDetector(mContext, this);
this.clickDetector = clickDetector;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("onDoubleTap :", "" + e.getAction());
clickDetector.doubleClick();
return super.onDoubleTap(e);
}

@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.d("onSingleTap :", "" + e.getAction());
clickDetector.singleClick();
return super.onSingleTapConfirmed(e);
}

@Override
public boolean onDown(MotionEvent e) {
//return super.onDown(e);
return true;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
Log.d("onLongPress :", "" + e.getAction());

}

Is there a Java library for calculating elapsed time?

Use Joda time's Period & PeriodFormatter. Example.



Related Topics



Leave a reply



Submit